轉(zhuǎn)載自 http://www.javaeye.com/topic/413580#1064514
一家公司生產(chǎn)兩個系列的產(chǎn)品
A系列, 食品里: milk,meat,noodle
B系列, 與A系列相對應的餐具,Spoon,Knife,Chopsticks
產(chǎn)品有兩個系列,在A系列某個位置的產(chǎn)品,在B系列一定有一個對應的產(chǎn)品, 牛奶--湯勺, 肉-刀, 面條--筷子
抽象產(chǎn)品系列之一, 食品類接口與三個具體的食品類
1: package Food;
2: public interface Food {
3: public String getMyFood();
4: }
5:
6: public class Meat implements Food {
7:
8: public String getMyFood() {
9:
10: return "Meat";
11: }
12:
13: }
14:
15: public class Milk implements Food {
16:
17: public String getMyFood() {
18:
19: return "Milk";
20: }
21:
22: }
23:
24: public class Noodle implements Food {
25:
26: public String getMyFood() {
27:
28: return "Noodle";
29:
30: }
31:
32: }
抽象產(chǎn)品系列之二, 餐具類接口與三個具體的餐具類
1: package TableWare;
2:
3: public interface TableWare {
4: public String getMyTableWare();
5: }
6:
7: public class Knife implements TableWare {
8:
9: public String getMyTableWare() {
10: return "Knife";
11: }
12:
13: }
14:
15: public class Spoon implements TableWare {
16:
17: public String getMyTableWare() {
18: return "Spoon";
19: }
20:
21: }
22:
23: public class Chopsticks implements TableWare {
24:
25: public String getMyTableWare() {
26: return "Chopsticks";
27: }
28:
29: }
30:
抽象工廠接口,它是抽象工廠模式的核心,與具體的產(chǎn)品邏輯無關(guān)
1: public interface KitchenFactory {
2: public Food getFood();
3: public TableWare getTableWare();
4: }
具體工廠A,生產(chǎn)牛奶和它對應的湯勺
1: public class KitchenFactoryA implements KitchenFactory {
2:
3: public Food getFood() {
4:
5: return new Milk();
6: }
7:
8: public TableWare getTableWare() {
9: // TODO Auto-generated method stub
10: return new Spoon();
11: }
12:
13: }
具體工廠B,生產(chǎn)肉和它對應的刀子
1: public class KitchenFactoryB implements KitchenFactory {
2:
3: public Food getFood() {
4:
5: return new Meat();
6: }
7:
8: public TableWare getTableWare() {
9:
10: return new Knife();
11: }
12:
13: }
具體工廠C,生產(chǎn)面條和它對應的筷子
1: public class KitchenFactoryC implements KitchenFactory {
2:
3: public Food getFood() {
4:
5: return new Noodle();
6: }
7:
8: public TableWare getTableWare() {
9:
10: return new Chopsticks();
11: }
12:
13: }
在什么情形下應當使用抽象工廠模式
在以下情況下,應當考慮使用抽象工廠模式。
首先,一個系統(tǒng)應當不依賴于產(chǎn)品類實例被創(chuàng)立,組成,和表示的細節(jié)。這對于所有形態(tài)的工廠模式都是重要的。
其次,這個系統(tǒng)的產(chǎn)品有多于一個的產(chǎn)品族。
第三,同屬于同一個產(chǎn)品族的產(chǎn)品是設(shè)計成在一起使用的。這一約束必須得在系統(tǒng)的設(shè)計中體現(xiàn)出來。
最后,不同的產(chǎn)品以一系列的接口的面貌出現(xiàn),從而使系統(tǒng)不依賴于接口實現(xiàn)的細節(jié)。
其中第二丶第三個條件是我們選用抽象工廠模式而非其它形態(tài)的工廠模式的關(guān)鍵性條件。