耦合关系:
动机(Motivation):
在软件系统中,由于需求的变化,"
这个对象的具体实现"经常面临着剧烈的变化,但它却
有比较稳定的接口。
如何应对这种变化呢?提供一种封装机制来隔离出"这个易变对象"的变化,从而保持系统中"其它依赖的对象"不随需求的变化而变化。
意图(Intent):
定义一个用户创建对象的接口,让子类决定实例哪一个类。Factory Method使一个类的实例化延迟到子类。
----------《设计模式》GOF
结构图(Struct):
生活实例:
适用性:
1.当一个类不知道它所必须创建的对象类的时候。
2.当一个类希望由它子类来指定它所创建对象的时候。
3.当类将创建对象的职责委托给多个帮助子类中的某个,并且你希望将哪一个帮助子类是代理者这一信息局部化的时候。
实例代码:
CarFactory类:
1
public
abstract
class
CarFactory
2
{
3
public
abstract
Car CarCreate();
4
}
Car类:
1
public
abstract
class
Car
2
{
3
public
abstract
void
StartUp();
4
public
abstract
void
Run();
5
public
abstract
void
Stop();
6
7
}
HongQiCarFactory类:
1
public
class
HongQiCarFactory:CarFactory
2
{
3
public
override
Car CarCreate()
4
{
5
return
new
HongQiCar();
6
}
7
}
BMWCarFactory类:
1
public
class
BMWCarFactory:CarFactory
2
{
3
public
override
Car CarCreate()
4
{
5
return
new
BMWCar();
6
}
7
}
HongQiCar类:
1
public
class
HongQiCar:Car
2
{
3
public
override
void
StartUp()
4
{
5
Console.WriteLine(
"
Test HongQiCar start-up speed!
"
);
6
}
7
public
override
void
Run()
8
{
9
Console.WriteLine(
"
The HongQiCar run is very quickly!
"
);
10
}
11
public
override
void
Stop()
12
{
13
Console.WriteLine(
"
The slow stop time is 3 second
"
);
14
}
15
}
BMWCar类:
1
public
class
BMWCar:Car
2
{
3
public
override
void
StartUp()
4
{
5
Console.WriteLine(
"
The BMWCar start-up speed is very quickly
"
);
6
}
7
public
override
void
Run()
8
{
9
Console.WriteLine(
"
The BMWCar run is quitely fast and safe!!!
"
);
10
}
11
public
override
void
Stop()
12
{
13
Console.WriteLine(
"
The slow stop time is 2 second
"
);
14
}
15
}
app.config
1
<?
xml version
=
"
1.0
"
encoding
=
"
utf-8
"
?>
2
<
configuration
>
3
<
appSettings
>
4
<
add key
=
"
No1
"
value
=
"
HongQiCarFactory
"
/>
5
<
add key
=
"
No2
"
value
=
"
BMWCarFactory
"
/>
6
</
appSettings
>
7
</
configuration
>
Program类:
1
class
Program
2
{
3
static
void
Main(
string
[] args)
4
{
5
Console.WriteLine(
"
Please Enter Factory Method No:
"
);
6
Console.WriteLine(
"
******************************
"
);
7
Console.WriteLine(
"
no Factory Method
"
);
8
Console.WriteLine(
"
1 HongQiCarFactory
"
);
9
Console.WriteLine(
"
2 BMWCarFactory
"
);
10
Console.WriteLine(
"
******************************
"
);
11
int
no
=
Int32.Parse(Console.ReadLine().ToString());
12
string
factoryType
=
ConfigurationManager.AppSettings[
"
No
"
+
no];
13
//
CarFactory factory = new HongQiCarFactory();
14
CarFactory factory
=
(CarFactory)Assembly.Load(
"
FactoryMehtod
"
).CreateInstance(
"
FactoryMehtod.
"
+
factoryType); ;
15
Car car
=
factory.CarCreate();
16
car.StartUp();
17
car.Run();
18
car.Stop();
19
20
}
21
}
Factory Method 模式的几个要点:
Factory Method模式主要用于
隔离类对象的使用者和具体类型之间的耦合关系。面对一个经常变化的具体类型,紧耦合关系会导致软件的脆弱。
Factory Method模式通过面向对象的手法,将所要创建的具体对象工作延迟到子类,从而实现一种扩展(而非更改)的策略,较好地解决了这种紧耦合关系。
Factory Mehtod模式
解决"单个对象"的需求变化,
AbstractFactory模式
解决"系列对象"的需求变化,
Builder模式
解决"对象部分"的需求变化。