当前位置:网站首页>Factory mode

Factory mode

2022-06-24 16:33:00 HLee

Create an interface :Shape.java

public interface Shape {
   void draw();
}

Create entity classes that implement interfaces :Rectangle.java,Square.java,Circle.java

public class Rectangle implements Shape {

   @Override
   public void draw() {
      System.out.println("Inside Rectangle::draw() method.");
   }
}
public class Square implements Shape {

   @Override
   public void draw() {
      System.out.println("Inside Square::draw() method.");
   }
}
public class Circle implements Shape {

   @Override
   public void draw() {
      System.out.println("Inside Circle::draw() method.");
   }
}

Create a factory , Generate object of entity class based on given information :ShapeFactory.java

public class ShapeFactory {
    
   // Use  getShape  Method to get the shape type object 
   public Shape getShape(String shapeType){
      if(shapeType == null){
         return null;
      }        
      if(shapeType.equalsIgnoreCase("CIRCLE")){
         return new Circle();
      } else if(shapeType.equalsIgnoreCase("RECTANGLE")){
         return new Rectangle();
      } else if(shapeType.equalsIgnoreCase("SQUARE")){
         return new Square();
      }
      return null;
   }
}

Using the plant , Get the object of entity class by passing type information :FactoryPatternDemo.java

public class FactoryPatternDemo {

   public static void main(String[] args) {
      ShapeFactory shapeFactory = new ShapeFactory();

      // obtain  Circle  The object of , And call its  draw  Method 
      Shape shape1 = shapeFactory.getShape("CIRCLE");
      // call  Circle  Of  draw  Method 
      shape1.draw();

      // obtain  Rectangle  The object of , And call its  draw  Method 
      Shape shape2 = shapeFactory.getShape("RECTANGLE");
      // call  Rectangle  Of  draw  Method 
      shape2.draw();

      // obtain  Square  The object of , And call its  draw  Method 
      Shape shape3 = shapeFactory.getShape("SQUARE");
      // call  Square  Of  draw  Method 
      shape3.draw();
   }
}

 Output :
Inside Circle::draw() method.
Inside Rectangle::draw() method.
Inside Square::draw() method.
原网站

版权声明
本文为[HLee]所创,转载请带上原文链接,感谢
https://yzsam.com/2021/04/20210416184427840c.html

随机推荐