1. 程式人生 > >創建型設計模式(工廠模式)

創建型設計模式(工廠模式)

ava lsi else if 接口 spa 模式 cas 並且 return

在工廠模式中,我們創建對象而不將創建邏輯暴露給客戶端。

首先,我們設計一個接口來表示Shape。

public interface Shape {
   void draw();
}

然後我們創建實現接口的具體類。  

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.");
   }
}

核心工廠模式是一個Factory類。以下代碼顯示了如何為Shape對象創建Factory類。

ShapeFactory類基於傳遞給getShape()方法的String值創建Shape對象。如果String值為CIRCLE,它將創建一個Circle對象。

public class ShapeFactory {
  
   //use getShape method to get object of type shape 
   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;
   }
}

  以下代碼具有main方法,並且它使用Factory類通過傳遞類型等信息來獲取具體類的對象。

public class Main {

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

      //get an object of Circle and call its draw method.
      Shape shape1 = shapeFactory.getShape("CIRCLE");

      //call draw method of Circle
      shape1.draw();

      //get an object of Rectangle and call its draw method.
      Shape shape2 = shapeFactory.getShape("RECTANGLE");

      //call draw method of Rectangle
      shape2.draw();

      //get an object of Square and call its draw method.
      Shape shape3 = shapeFactory.getShape("SQUARE");

      //call draw method of circle
      shape3.draw();
   }
}

  

  

  

創建型設計模式(工廠模式)