1. 程式人生 > 實用技巧 >工廠模式(建立型)

工廠模式(建立型)

設計模式的3個分類:建立型模式、結構型模式、行為型模式

工廠模式定義:

定義了一個建立物件的介面,但由子類決定要例項化的類是哪一個。工廠方法讓類把例項化推遲到子類。

工廠模式圖示:

1.簡單工廠示例:

圖示:

程式碼實現:

/**
 * 定義Shape介面
 */
public interface Shape {

    void draw();
}

//Shape介面的實現類
public class Circle implements Shape{

    @Override
    public void draw() {
        System.out.println("Circle Draw!");
    }
}

public class Square implements Shape{

    @Override
    public void draw() {
        System.out.println("Square Draw!");
    }
}

public class Rectangle implements Shape{

    @Override
    public void draw() {
        System.out.println("Rectangle Draw!");
    }
}

//工廠方法
public class ShapeFactory {

    public Shape getShape(String shapeType) {

        if(shapeType == null) {
            return null;
        }
        if(shapeType.equalsIgnoreCase("circle")) {
            return new Circle();
        } else if(shapeType.equalsIgnoreCase("square")) {
            return new Square();
        } else if(shapeType.equalsIgnoreCase("rectangle")) {
            return new Rectangle();
        }
        return null;
    }
}

//Test
public class FactoryPatternDemo {

    public static void main(String[] args) {

        ShapeFactory factory = new ShapeFactory();

        //獲取Circle物件,並呼叫它的draw方法
        Shape shape1 = factory.getShape("circle");
        shape1.draw();

        //獲取Square物件,並呼叫它的draw方法
        Shape shape2 = factory.getShape("square");
        shape2.draw();

        //獲取Rectangle物件,並呼叫它的draw方法
        Shape shape3 = factory.getShape("rectangle");
        shape3.draw();

    }
}