设计模式-简单工厂模式(二)

2023-05-03 14:37:01 浏览数 (1)

定义一个简单工厂类 ShapeFactory,它包含一个静态方法 createShape,根据用户输入的指令创建不同类型的图形对象。

代码语言:javascript复制
public class ShapeFactory {
    public static Shape createShape(String type, double... params) {
        if (type.equals("circle")) {
            return new Circle(params[0]);
        } else if (type.equals("square")) {
            return new Square(params[0]);
        } else if (type.equals("rectangle")) {
            return new Rectangle(params[0], params[1]);
        } else {
            throw new IllegalArgumentException("Unsupported shape type");
        }
    }
}

客户端使用简单工厂模式创建不同类型的图形对象,示例代码如下:

代码语言:javascript复制
public class Client {
    public static void main(String[] args) {
        Shape circle = ShapeFactory.createShape("circle", 2.0);
        System.out.println("Circle perimeter: "   circle.calculatePerimeter());
        System.out.println("Circle area: "   circle.calculateArea());

        Shape square = ShapeFactory.createShape("square", 2.0);
        System.out.println("Square perimeter: "   square.calculatePerimeter());
        System.out.println("Square area: "   square.calculateArea());

        Shape rectangle = ShapeFactory.createShape("rectangle", 2.0, 3.0);
        System.out.println("Rectangle perimeter: "   rectangle.calculatePerimeter());
        System.out.println("Rectangle area: "   rectangle.calculateArea());
    }
}

输出结果如下:

代码语言:javascript复制
Circle perimeter: 12.566370614359172
Circle area: 12.566370614359172
Square perimeter: 8.0
Square area: 4.0
Rectangle perimeter: 10.0
Rectangle area: 6.0

在客户端代码中,我们只需要知道要创建的图形类型和参数即可,无需关心具体的创建过程。通过简单工厂模式,客户端与具体产品类解耦,可以轻松地扩展新的产品类。

0 人点赞