具体工厂类SquareFactory:
public class SquareFactory implements ShapeFactory {
private double side;
public SquareFactory(double side) {
this.side = side;
}
@Override
public Shape createShape() {
return new Square(side);
}
}具体工厂类RectangleFactory:
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);
}
}客户端调用:
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());
}
}运行结果:
Circle perimeter: 31.41592653589793
Circle area: 78.53981633974483
Square perimeter: 16.0
Square area: 16.0
Rectangle perimeter: 14.0
Rectangle area: 12.0原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。