一尘不染

当具体对象采用不同的构造函数参数时,在Java中为工厂

java

我正在尝试在Java中实现Factory模式。我有一个名为Shape的类,该类由Circle和Triangle扩展。问题在于Shape构造函数仅获取2个参数,而Circle则获取3个参数,Triangle也是如此(由于与Circle相同,因此我不会在代码部分中显示)。为了更好地演示它:

    private interface ShapeFactory{
        public Shape create(int x, int y);
    }

    private class CircleFactory implements ShapeFactory{
        public Shape create(float radius, int x, int y){ //error
            return new Circle(radius, x,y);
        }
    }

任何想法如何克服这个问题?我一定不能从工厂内部接收用户的输入(必须从外部接收)。

谢谢!


阅读 174

收藏
2020-12-03

共1个答案

一尘不染

您有两种选择:

1)抽象工厂

RectangularShape extends Shape

RoundShape extends Shape

RectangularShapeFactoryRoundShapeFactory

2)构建器(另请参见有效Java中的第2项)

public Shape {
    private final int x;
    private final int y;
    private final double radius;

    private Shape(Builder builder) {
        x = builder.x;
        y = builder.y;
        radius = builder.radius;
    }

    public static class Builder {
        private final int x;
        private final int y;
        private double radius;

        public Builder(int x, int y) {
            this.x = x;
            this.y = y;
        }

        public Builder radius(double radius) {
            this.radius = radius;
            return this;
        }

        public Shape build() {
            return new Shape(this);
        }    
    }
}

//in client code

    Shape rectangle = new Shape.Builder(x,y).build();
    Shape circle = new Shape.Builder(x,y).radius(radiusValue).build();
2020-12-03