您的位置:首页 > 其它

原型模式(prototype pattern)

2010-11-26 18:24 155 查看
今天有空学习了一下设计模式-> 原型模式(prototype pattern),记录一下笔记做一个初稿,记录一下该模式的知识要点和一些自己的理解,有不对的记得留言改正,灰常感激。

实现原理:创建指定类型的对象,以该对象为原型通过拷贝(深拷贝 或 浅拷贝,关于拷贝初稿就不说了,有空细致研究一下)方式创建新对象。

结构图(摘的,感谢TerryLee,无量天尊):



适用范围(场景):个人感觉该模式适合在需要动态创建很多同类型的对象,同时对象间的属性有的不相同。比如说游戏中碰到了一队的怪,这队怪中有有一个队长,队长一定比小喽啰强一些,这时创建这一队的怪要使用什么方式?原型模式呗(这个比较适合)。以小怪为原型,拷贝n多个出来,将其中的一个修改体力和攻击力,就成队长了;再比如说画板的调色板,里面有n多的颜色,这些要创建出来也很费劲,如果使用抽象工厂模式(abstract factory)也不是不可以,问题是颜色如果有100来个那就得弄出100来个的该颜色的工厂类,这......体力活啊。还是使用原型模式(prototype pattern)吧。(以上实例据来自院子,感谢,再感谢)

代码实例:
出个例子吧,一个办公室,5个职员,1个boss 用原型模式(prototype pattern)表现一下
1、职员、boss都是人,所以抽象一下,几个属性:职位、姓名,一个方法:显示身份

using System;

/// <summary>
///Humen 干什么的都是人啊
/// </summary>
[Serializable]
public abstract class Human
{
public Human()
{
}

public Human(string Job, string Name)
{
this._Job = Job;
this._Name = Name;
}

private string _Job;
private string _Name;

public string Job
{
get { return _Job; }
set { _Job = value; }
}

public string Name
{
get { return _Name; }
set { _Name = value; }
}

public abstract void Show();

public abstract Human Clone(bool IsDeepCopy);
}


2、实现员工特点的人 Worker

using System;
using System.Collections.Generic;
using System.Web;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

/// <summary>
///Worker 人里面有员工啊,员工也是人啊
/// </summary>
[Serializable]
public class Worker:Human
{
public Worker()
{
}

public Worker(string Job, string Name)
: base(Job, Name)
{ }

public override void Show()
{
System.Web.HttpContext.Current.Response.Write(string.Format("职位:{0} 姓名:{1}<br />", this.Job, this.Name));
}

public override Human Clone(bool IsDeepCopy)
{
Human hu;
if (IsDeepCopy)
{
MemoryStream memoryStream = new MemoryStream();
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(memoryStream, this);
memoryStream.Position = 0;
hu = (Worker)formatter.Deserialize(memoryStream);
}
else
hu = (Worker)this.MemberwiseClone();
return hu;
}
}


3、弄一个生人的类Mather

using System;
using System.Collections.Generic;

/// <summary>
///Mother 的摘要说明
/// </summary>
public class Mother
{
public Mother()
{
//
//TODO: 在此处添加构造函数逻辑
//
}

public List<Human> CreateDepartHumen(Human hu)
{
List<Human> depart = new List<Human>();
Human w1 = hu.Clone(true) as Human;
w1.Job = "经理";
w1.Name = "boss";
depart.Add(w1);
for (int i = 0; i < 5; i++)
{
Human w = hu.Clone(true);
w.Job = "职员";
w.Name = "职员姓名" + (i + 1).ToString();
depart.Add(w);
}
return depart;
}
}


4、开始生成了

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

Human hu = new Worker();
Mother mo = new Mother();
List<Human> depart = mo.CreateDepartHumen(hu);

foreach (Worker wo in depart)
{
wo.Show();
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: