具体工厂类SquareFactory:
代码语言:javascript复制public class SquareFactory implements ShapeFactory {
private double side;
public SquareFactory(double side) {
this.side = side;
}
@Override
public Shape createShape() {
return new Square(side);
}
}
具体工厂类RectangleFactory:
代码语言:javascript复制public class RectangleFactory implements ShapeFactory {
private double width;
private double height;
public RectangleFactory(double width, double height) {
this.width = width;
this.height = height;
}
@Override
public Shape createShape() {
return new Rectangle(width, height);
}
}
客户端调用:
代码语言:javascript复制public class Client {
public static void main(String[] args) {
// 创建具体工厂类的对象
ShapeFactory circleFactory = new CircleFactory(5);
ShapeFactory squareFactory = new SquareFactory(4);
ShapeFactory rectangleFactory = new RectangleFactory(3, 4);
// 调用工厂方法创建具体产品类的对象
Shape circle = circleFactory.createShape();
Shape square = squareFactory.createShape();
Shape rectangle = rectangleFactory.createShape();
// 使用具体产品类的对象
System.out.println("Circle perimeter: " circle.calculatePerimeter());
System.out.println("Circle area: " circle.calculateArea());
System.out.println("Square perimeter: " square.calculatePerimeter());
System.out.println("Square area: " square.calculateArea());
System.out.println("Rectangle perimeter: " rectangle.calculatePerimeter());
System.out.println("Rectangle area: " rectangle.calculateArea());
}
}
运行结果:
代码语言:javascript复制Circle perimeter: 31.41592653589793
Circle area: 78.53981633974483
Square perimeter: 16.0
Square area: 16.0
Rectangle perimeter: 14.0
Rectangle area: 12.0