1.簡單工廠
Sample:介面
SampleA:Sample介面實現類A
SampleB:Sample介面實現類B
Factory:Sample的工廠類
複製程式碼
Factory類程式碼
public class Factory {
public static Sample creator(int which) {
switch (which) {
case 1:
return new SampleA();
case 2:
return new SampleB();
default:
return null;
}
}
}
複製程式碼
2.抽象工廠
Sample:介面
SampleA:Sample介面實現類A
SampleB:Sample介面實現類B
Sample2:介面
Sample2A:Sample2介面實現類A
Sample2B:Sample2介面實現類B
Factory:Sample、Sample2的抽象工廠類
SimpleFactory:Factory的實現類1
BombFactory:Factory的實現類2
複製程式碼
Factory類程式碼
public abstract class Factory {
public abstract Sample creator();
public abstract Sample2 creator(String name);
}
複製程式碼
SimpleFactory類程式碼
public class SimpleFactory extends Factory {
@Override
public Sample creator() {
return new SampleA();
}
@Override
public Sample2 creator(String name) {
return new Sample2A();
}
}
複製程式碼
BombFactory類程式碼
public class BombFactory extends Factory {
@Override
public Sample creator() {
return new SampleB();
}
@Override
public Sample2 creator(String name) {
return new Sample2B();
}
}
複製程式碼
抽象工廠還有另外一個關鍵要點,是因為 SimpleFactory內,生產Sample和生產Sample2的方法之間有一定聯絡,所以才要將這兩個方法捆綁在一個類中,這個工廠類有其本身特徵,也許製造過程是統一的,比如:製造工藝比較簡單,所以名稱叫SimpleFactory。