代码改变世界

设计模式之原型模式(Prototype)

2010-01-18 20:39  key_sky  阅读(160)  评论(0编辑  收藏  举报

原型模式(Prototype):用原型实例指定创建对象的总类,并且通过拷贝这些原型创建新的对象。
MemberwiseClone():如果字段是值类型的,则对该字段执行逐位复制,如果字段是引用类型,则复制引用但不复制引用的对象。

Protype.cs:

代码
using System;
using System.Collections.Generic;
using System.Text;


//原型模式(Prototype):用原型实例指定创建对象的总类,并且通过拷贝这些原型创建新的对象。
//MemberwiseClone():如果字段是值类型的,则对该字段执行逐位复制,如果字段是引用类型,则
//复制引用但不复制引用的对象。
namespace Prototype
{
class Prototype1
{
}
//原型类
abstract class Prototype
{
private string id;

public Prototype(string id)
{
this.id = id;
}

public string Id
{
get { return id; }
}

public abstract Prototype Clone();
}
//具体原型类
class ConcretePrototype1 : Prototype
{
public ConcretePrototype1(string id)
:
base(id)
{
}

public override Prototype Clone()
{
return (Prototype)this.MemberwiseClone();
//浅表副本
}
}
}

 

Program.cs:

代码
using System;
using System.Collections.Generic;
using System.Text;

namespace Prototype
{
class Program
{
static void Main(string[] args)
{
ConcretePrototype1 p1
= new ConcretePrototype1("I");
ConcretePrototype1 c1
= (ConcretePrototype1)p1.Clone();
Console.WriteLine(
"Cloned:{0}", c1.Id);

Console.Read();
}
}
}

运行结果:

Cloned:I