具体产品类Square:
代码语言:javascript复制public class Square extends Shape {
private double side;
public Square(double side) {
this.side = side;
}
@Override
public double calculatePerimeter() {
return 4 * side;
}
@Override
public double calculateArea() {
return side * side;
}
}
具体产品类Rectangle:
代码语言:javascript复制public class Rectangle extends Shape {
private double width;
private double height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
@Override
public double calculatePerimeter() {
return 2 * (width height);
}
@Override
public double calculateArea() {
return width * height;
}
}
抽象工厂类ShapeFactory:
代码语言:javascript复制public interface ShapeFactory {
// 创建具体产品类的对象
public Shape createShape();
}
具体工厂类CircleFactory:
代码语言:javascript复制public class CircleFactory implements ShapeFactory {
private double radius;
public CircleFactory(double radius) {
this.radius = radius;
}
@Override
public Shape createShape() {
return new Circle(radius);
}
}