1、工厂模式

以画图形为例:Shape 接口和实现 Shape 接口的实体类Rectangle、Square、Circle

类图
  • 形状接口
public interface Shape {
    void draw();
}
  • 实现类
public class Circle implements Shape {
    @Override
    public void draw() {
        System.out.println("Draw Circle!");
    }
}
public class Square implements Shape {
    @Override
    public void draw() {
        System.out.println("Draw Square!");
    }
}
public class Rectangle implements Shape {
    @Override
    public void draw() {
        System.out.println("Draw Rectangle!");
    }
}
  • 工厂
public class ShapeFactory {

    public Shape getShape(String shapeType){
        switch (shapeType.toUpperCase()){
            case "CIRCLE":
                return new Circle();
            case "RECTANGLE":
                return new Rectangle();
            case "SQUARE":
                return new Square();
            default:
                return null;
        }
    }
}
  • 测试类
public class TestFactory {
    public static void main(String[] args) {
        ShapeFactory shapeFactory = new ShapeFactory();

        //图形:rectangle
        Shape shape1 = shapeFactory.getShape("rectangle");
        shape1.draw();

        //图形:circle
        Shape shape2 = shapeFactory.getShape("circle");
        shape2.draw();

        //图形:square
        Shape shape3 = shapeFactory.getShape("square");
        shape3.draw();
    }
}
  • 结果:
Draw Rectangle!
Draw Circle!
Draw Square!

你可能感兴趣的:(1、工厂模式)