1 回答
TA贡献1833条经验 获得超4个赞
您的解决方案不是最佳的,因为:1)您必须为具体的构造函数创建专用的构造函数Shape,并且您失去了参数的类型检查(在编译时)。2)init具体工厂的方法容易出错。
这就是我要做的。具体工厂应该携带具体构造函数的参数Shape,但不能作为不确定的字符串(如果从用户输入获取字符串,请在创建具体工厂之前转换它们):
public interface ShapeFactory {
public Shape make(String shapeType);
}
public class ShapeFactoryImpl implements ShapeFactory {
private int circleRadius;
private int rectangleLength;
private int rectangleBreadth;
public ShapeFactoryImpl(int circleRadius, int rectangleLength, int rectangleBreadth){
this.circleRadius = circleRadius;
this.rectangleLength = rectangleLength;
this.rectangleBreadth = rectangleBreadth;
}
public Shape make(String shapeType) {
switch (shapeType) {
case "Circle": return new Circle(this.circleRadius);
case "Rectangle": return new Rectangle(this.rectangleLength, this.rectangleBreadth);
default: throw new Exception("...");
}
}
}
客户不需要知道ShapeFactory他正在使用的混凝土,也不必担心Shape他得到的混凝土。依赖关系是相反的:发挥关键作用的是抽象,而不是细节。但如果可能的形状数量增加,您将得到一个具有许多相似参数的构造函数。这是另一个解决方案:
public class ShapeFactoryImpl implements ShapeFactory {
private Shape circle;
private Shape rectangle;
public ShapeFactoryImpl(Circle circle, Rectangle rectangle){
this.circle = circle;
this.rectangle = rectangle;
}
public Shape make(String shapeType) {
switch (shapeType) {
case "Circle": return this.circle.clone();
case "Rectangle": return this.rectangle.clone();
default: throw new Exception("...");
}
}
}
这更好,因为您不会混合参数:每种混凝土都Shape包含自己的参数。如果你想让它更灵活,你可以使用 Map 将交换机的责任移出具体工厂:
public class ShapeFactoryImpl implements ShapeFactory {
private Map<String, Shape> shapeByType;
public ShapeFactoryImpl(Map<String, Shape> shapeByType){
this.shapeByType = shapeByType;
}
public Shape make(String shapeType) {
Shape shape = this.shapeByType.get(Type).clone();
if (shape == null) {
throw new Exception("...");
}
return shape;
}
}
我什至会使用 anenum来代替形状类型而不是字符串,并使用 anEnumMap来处理开关:
public class ShapeFactoryImpl implements ShapeFactory {
private EnumMap<ShapeType, Shape> shapeByType;
public ShapeFactoryImpl(Map<ShapeType, Shape> shapeByType){
this.shapeByType = shapeByType;
}
public Shape make(ShapeType shapeType) {
return this.shapeByType.get(Type).clone();
}
}
客户端必须知道Shape接口ShapeFactory和ShapeType枚举。“服务器”提供具体ShapeFactoryImpl实例。
添加回答
举报