我的主義學習簡單工廠模式,我想知道如果我廠所有的方法都是有效的這樣一種模式:所有這些方法簽名是否適用於簡單工廠模式?
public class Bmw implements Car {
private String color;
private boolean hasXDrive;
public Bmw() {
}
public Bmw(String color) {
this.color = color;
}
public Bmw(String color, boolean hasXDrive) {
this.color = color;
this.hasXDrive = hasXDrive;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public boolean isHasXDrive() {
return hasXDrive;
}
public void setHasXDrive(boolean hasXDrive) {
this.hasXDrive = hasXDrive;
}
}
public class Audi implements Car {
private String color;
private int turnAssistLevel;
public Audi() {
}
public Audi(String color) {
this.color = color;
}
public Audi(String color, int turnAssistLevel) {
this.color = color;
this.turnAssistLevel = turnAssistLevel;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public int getTurnAssistLevel() {
return turnAssistLevel;
}
public void setTurnAssistLevel(int turnAssistLevel) {
this.turnAssistLevel = turnAssistLevel;
}
}
public class SimpleCarFactory {
// 1. make empty cars
public Car makeCar(CarType carType) {
switch (carType) {
case AUDI:
return new Audi();
case BMW:
return new Bmw();
default:
throw new RuntimeException("No such car type!");
}
}
// 2. make cars with colors
public Car makeCarWithColor(CarType carType, String color) {
switch (carType) {
case AUDI:
return new Audi(color);
case BMW:
return new Bmw(color);
default:
throw new RuntimeException("No such car type!");
}
}
// 3. BMW has an option that differentiate it from any other car. We cannot use a general car factory anymore
public Car makeBmw(String color, boolean hasXDrive) {
return new Bmw(color, hasXDrive);
}
// 4. Audi has a turnAssistLevel option
public Car makeAudi(String color, int turnAssistLevel) {
return new Audi(color, turnAssistLevel);
}
// 5. The same as #1, only it is static now make empty cars
public static Car staticMakeCar(CarType carType) {
switch (carType) {
case AUDI:
return new Audi();
case BMW:
return new Bmw();
default:
throw new RuntimeException("No such car type!");
}
}
}
我在代碼中添加註釋的方法的變體。我問這些問題,因爲通常情況下,你創建一個基於一些鑑別器(CarType)的子類。但是你也可以有構造函數參數。
此外,我不知道當你的相關對象有不同的構造函數時該怎麼辦。
請告訴我SimpleCarFactory的哪些方法符合簡單的工廠模式?
親切的問候,
您可能會在http://softwareengineering.stackexchange.com/ – Pace
@Pet上得到更好的答案我會說http://codereview.stackexchange.com/可能會更好。 –
@Pace在引用其他網站時,通常很有幫助的一點是[交叉發佈是皺眉了](http://meta.stackexchange.com/tags/cross-posting/info) – gnat