抽象工厂模式:
提供一个接口,用于创建相关的依赖对象的家族,而不需要明确指定类
该模式符合依赖倒转原则,高级对象不依赖于低级对象,两者都依赖于抽象。
我个人认为就是高级对象抽象成高级接口,低级对象抽象成低级接口,2者的依赖关系转化为2种接口的之间的依赖,而非对象之间的依赖关系,从而达到松耦合的效果。
抽象工厂强调的就是封装,将需要不同的对象创建部分放在不同的工厂里面,有选择性的返回不同的对象,以下我以造车工厂--汽车为例:
1
public interface IShowProduct
2
{
3
void ShowProduct();
4
}
5
6
public interface IAbstractFactory
7
{
8
IFactory CreateFactory(string name);
9
}
10
11
public interface IFactory :IShowProduct
12
{
13
ICar CreateCar(string name);
14
15
}
16
17
public interface ICar : IShowProduct
18
{
19
20
}
21
22
public class AbstractFactory : IAbstractFactory
23
{
24
IAbstractFactory Members
36
}
37
38
39
public class Factory_1 : IFactory
40
{
41
42
IFactory Members
54
55
IShowProduct Members
63
}
64
65
public class Factory_2 : IFactory
66
{
67
68
IFactory Members
80
81
IShowProduct Members
89
}
90
91
public class BMW : ICar
92
{
93
94
IShowProduct Members
102
}
103
104
public class QQ : ICar
105
{
106
107
IShowProduct Members
115
}
116
117
public class Hyc : ICar
118
{
119
120
IShowProduct Members
128
}
129
130
public class Hgpc : ICar
131
{
132
133
IShowProduct Members
141
}
142
143
public class Mc : ICar
144
{
145
146
IShowProduct Members
154
}
155
156
class Program
157
{
158
static void Main(string[] args)
159
{
160
string carName = "大奔驰";
161
string factoryName = "工厂1";
162
Console.WriteLine(string.Format("我选择了{0},要制造{1}", factoryName, carName));
163
IAbstractFactory abstractfactory = new AbstractFactory();
164
IFactory factory = abstractfactory.CreateFactory(factoryName);
165
factory.ShowProduct();
166
ICar car = factory.CreateCar(carName);
167
car.ShowProduct();
168
169
carName = "QQ";
170
factoryName = "工厂1";
171
Console.WriteLine(string.Format("我选择了{0},要制造{1}", factoryName, carName));
172
173
IFactory factory_2 = abstractfactory.CreateFactory(factoryName);
174
factory_2.ShowProduct();
175
car = factory_2.CreateCar(carName);
176
car.ShowProduct();
177
178
Console.Read();
179
}
180
}

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

36

37

38

39

40

41

42

54

55

63

64

65

66

67

68

80

81

89

90

91

92

93

94

102

103

104

105

106

107

115

116

117

118

119

120

128

129

130

131

132

133

141

142

143

144

145

146

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180
