设计模式-工厂方法模式(二)

2023-05-03 14:45:31 浏览数 (1)

具体产品类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);
    }
}

0 人点赞