1 回答

TA貢獻(xiàn)1833條經(jīng)驗(yàn) 獲得超4個(gè)贊
您的解決方案不是最佳的,因?yàn)椋?)您必須為具體的構(gòu)造函數(shù)創(chuàng)建專用的構(gòu)造函數(shù)Shape,并且您失去了參數(shù)的類型檢查(在編譯時(shí))。2)init具體工廠的方法容易出錯(cuò)。
這就是我要做的。具體工廠應(yīng)該攜帶具體構(gòu)造函數(shù)的參數(shù)Shape,但不能作為不確定的字符串(如果從用戶輸入獲取字符串,請?jiān)趧?chuàng)建具體工廠之前轉(zhuǎn)換它們):
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他正在使用的混凝土,也不必?fù)?dān)心Shape他得到的混凝土。依賴關(guān)系是相反的:發(fā)揮關(guān)鍵作用的是抽象,而不是細(xì)節(jié)。但如果可能的形狀數(shù)量增加,您將得到一個(gè)具有許多相似參數(shù)的構(gòu)造函數(shù)。這是另一個(gè)解決方案:
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("...");
}
}
}
這更好,因?yàn)槟粫旌蠀?shù):每種混凝土都Shape包含自己的參數(shù)。如果你想讓它更靈活,你可以使用 Map 將交換機(jī)的責(zé)任移出具體工廠:
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;
}
}
我什至?xí)褂?anenum來代替形狀類型而不是字符串,并使用 anEnumMap來處理開關(guān):
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枚舉?!胺?wù)器”提供具體ShapeFactoryImpl實(shí)例。
添加回答
舉報(bào)