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枚舉?!胺掌鳌碧峁┚唧wShapeFactoryImpl實例。
添加回答
舉報