定义:用原型实例指定创建对象的种类,并通过拷贝这些原型创建新的对象。
原型图:
原型模式主要用于对象的复制,它的核心是就是类图中的原型类Prototype
原型模式是一种比较简单的模式,也非常容易理解,实现一个接口,重写一个方法即完成了原型模式。在实际应用中,原型模式很少单独出现。经常与其他模式混用,他的原型类Prototype也常用抽象类来替代
原型模式示例代码:
1
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
|
/// <summary>
/// 原型类
/// </summary>
abstract
class
Prototype
{
private
string
id;
public
Prototype(
string
id)
{
this
.id = id;
}
public
string
ID
{
get
{
return
id; }
}
/// <summary>
/// 克隆方法
/// </summary>
/// <returns></returns>
public
abstract
Prototype Clone();
}
/// <summary>
/// 具体的原型类
/// </summary>
class
ConcretePrototype : Prototype
{
public
ConcretePrototype(
string
id):
base
(id)
{}
public
override
Prototype Clone()
{
//克隆当前对象,浅复制
return
(Prototype)
this
.MemberwiseClone();
}
}
//客户端调用
class
Program
{
static
void
Main(
string
[] args)
{
ConcretePrototype p1 =
new
ConcretePrototype(
"I"
);
ConcretePrototype c1 = (ConcretePrototype)p1.Clone();
//克隆ConcretePrototype的对象p1就能得到新的实例c1.
Console.WriteLine(
"Cloned:{0}"
, c1.ID);
Console.Read();
}
}
|
代码比较的简单,只要还是为了更好的讲解核心的复制功能部分,原型模式还可以演变成很多种变化,这里就不在详细举例。