《java與模式》(閻宏) 學(xué)習(xí)筆記4(抽象工廠模式)
Posted on 2008-12-23 14:23 齊納爾多 閱讀(152) 評論(0) 編輯 收藏 所屬分類: 設(shè)計模式一、抽象工廠模式和工廠方法模式的區(qū)別是:
工廠方法模式是一個工廠具體類對應(yīng)一個產(chǎn)品的等級結(jié)構(gòu),而Abstract Factory 是一個工廠的具體類相應(yīng)多個產(chǎn)品的等級結(jié)構(gòu)
二、UML圖
三:簡單測試代碼如下:
工廠方法模式是一個工廠具體類對應(yīng)一個產(chǎn)品的等級結(jié)構(gòu),而Abstract Factory 是一個工廠的具體類相應(yīng)多個產(chǎn)品的等級結(jié)構(gòu)
二、UML圖

三:簡單測試代碼如下:
1
/**
2
* 抽象的工廠接口
3
*/
4
public interface IFactory {
5
/**
6
* 等級結(jié)構(gòu)A的工廠方法
7
*/
8
public IProductA factoryA();
9
10
/**
11
* 等級結(jié)構(gòu)B的工廠方法
12
*/
13
public IProductB factoryB();
14
}
15
public class FactoryA implements IFactory {
16
17
public IProductA factoryA() {
18
return new ProductA();
19
}
20
21
public IProductB factoryB() {
22
return new ProductB();
23
}
24
25
}
26
public class FactoryB implements IFactory {
27
28
public IProductA factoryA() {
29
return new ProductA();
30
}
31
32
public IProductB factoryB() {
33
return new ProductB();
34
}
35
36
}
37
/**
38
* 產(chǎn)品的接口
39
*/
40
41
public interface IProductA {
42
void helloA();
43
}
44
45
public class ProductA implements IProductA{
46
47
public void helloA() {
48
System.out.println("ProductA");
49
}
50
51
}
52
53
public interface IProductB {
54
void helloB();
55
}
56
public class ProductB implements IProductB{
57
58
public void helloB() {
59
System.out.println("Product B");
60
}
61
}
62
63
public class TestAbstractFactory {
64
65
/**
66
* 測試抽象工廠模式
67
* @param args
68
*/
69
public static void main(String[] args) {
70
IFactory f = new FactoryA();
71
f.factoryA().helloA();
72
f.factoryB().helloB();
73
74
IFactory f1 = new FactoryB();
75
f1.factoryA().helloA();
76
f1.factoryB().helloB();
77
}
78
79
}
80
81
82

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82
