设计模式之工厂模式

工厂模式提供了创建对象的最佳方式,创建对象时不会向客户端暴露创建逻辑,并且通过一个共同的接口指向新创建的对象。

1、创建一个接口

public interface Shape {
    void draw();
}

2、具体的对象

public class Circle implements Shape {
    @Override
    public void draw() {
        System.out.println("Inside Circle::draw() method.");
    }
}
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.");
    }
}

3、定义工厂类

public class ShapeFactory {
    
    public Shape getShape(String shapeType) {
        if (null == shapeType) {
            return null;
        }

        switch (shapeType) {
            case "CIRCLE":
                return new Circle();
            case "RECTANGLE":
                return new Rectangle();
            case "SQUARE":
                return new Square();
            default:
                return null;
        }
    }
}

4、测试

public class _Test {
    public static void main(String[] args) {
        ShapeFactory factory = new ShapeFactory();
        Shape shape1 = factory.getShape("CIRCLE");
        shape1.draw();
        Shape shape2 = factory.getShape("RECTANGLE");
        shape2.draw();
        Shape shape3 = factory.getShape("SQUARE");
        shape3.draw();
    }
}

 

上一篇:【基于obs开发推流工具教程】-direct主窗体渲染和创建数据源渲染分析


下一篇:Java单体应用 - 架构模式 - 03.设计模式-01.工厂模式