【Java】工廠模式

模式思想

  1. 約定一個接口
  2. 定義實現接口的實體類
  3. 定義用來獲取實體類的工廠類
  4. 調用工廠類

代碼實現

  1. 約定接口
package factory;

public interface Shape {

    void draw();
}
  1. 實現接口的實體類
  • Circle.java
package factory;

public class Circle implements Shape {

    public void draw() {
        System.out.println("Inside Circle::draw() method.");
    }
}
  • Rectangle.java
package factory;

public class Rectangle implements Shape {

    public void draw() {
        System.out.println("Inside Rectangle::draw() method.");
    }
}
  • Square.java
package factory;

public class Square implements Shape {

    public void draw() {
        System.out.println("Inside Square::draw() method.");
    }
}
  1. 定義工廠類
package factory;

public class ShapeFactory {

    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;
    }
}
  1. 調用工廠類
import factory.Shape;
import factory.ShapeFactory;

public class FactoryDemo {

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

        Shape shapeCircle = shapeFactory.getShape("Circle");
        shapeCircle.draw();

        Shape shapeRectangle = shapeFactory.getShape("Rectangle");
        shapeRectangle.draw();

        Shape shapeSquare = shapeFactory.getShape("Square");
        shapeSquare.draw();
    }
}

指導文檔

http://www.runoob.com/design-pattern/factory-pattern.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章