工廠模式程式碼

小白CAD發表於2020-12-01

1、介面建立

package com.seccen.homework.day7;

public interface Shape {
    // need to implement the interface
    void draw();
}

2、繼承介面的工廠:

      2.1、第一個工廠

package com.seccen.homework.day7;

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

      2.1、第二個工廠

package com.seccen.homework.day7;

public class Square implements Shape {

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

      2.1、第三個工廠

package com.seccen.homework.day7;

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

3、派發工廠工作的派發者

package com.seccen.homework.day7;

public class ShapeFactory {

    /**
     * create a factory to generate objects of entity classes based on the given information
     * @param shapeType
     * @return
     */
    public Shape getShape(String shapeType){
        if(shapeType == null){
            return null;
        }

        if(shapeType.equalsIgnoreCase("CIRCLE")){
            return new Circle();
        }
        if(shapeType.equalsIgnoreCase("RECTANGLE")){
            return new Rectangle();
        }
        if(shapeType.equalsIgnoreCase("SQUARE")){
            return new Square();
        }
        return null;
    }
}

4、使用者

package com.seccen.homework.day7;

public class FactoryMode {

    /**
     * Use this factory to obtain objects of entity classes by passing type information
     * @param args
     */
    public static void main(String[] args) {
            ShapeFactory shapeFactory = new ShapeFactory();
            Shape shape = shapeFactory.getShape("CIRCLE");
            shape.draw();

            Shape shape1 = shapeFactory.getShape("RECTANGLE");
            shape1.draw();

            Shape shape2 = shapeFactory.getShape("SQUARE");
            shape2.draw();
    }
}

在這裡插入圖片描述

相關文章