gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 20:35:24 26 4
gpt4 key购买 nike

我正在尝试在 Java 中实现工厂模式。我有一个名为 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);
}
}

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

谢谢!

最佳答案

你有两个选择:

1) Abstract Factory :

RectangularShape 扩展 Shape

RoundShape 扩展 Shape

RectangularShapeFactoryRoundShapeFactory

2) Builder (另见有效 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();

关于java - 当具体对象采用不同的构造函数参数时,Java 中的工厂,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13885836/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com