原型模式(Prototype)
原型模式,用原型实例指定创建对象的种类,并且通过这些原型创建新的对象。
代码
我们以一个简单的简历系统来阐述原型模式:
(注意:对于.NET而言,那个原型抽象类Prototype是用不着的,因为克隆实在是太常用了,所以.NET在System命名空间中提供了ICloneable接口,其中就是唯一的一个方法Clone(),这样你就只需要实现这个接口就可以完成原型模式了。)
1.代码如下:
简历类
using System;
namespace Prototype
{
//简历类
public class Resume:ICloneable
{
//姓名
private string name;
//性别
private string sex;
//年龄
private string age;
//工作时间段
private string timeArea;
//公司
private string company;
public Resume (string name)
{
this.name = name;
}
//设置个人信息
public void SetPersonalInfo(string sex,string age){
this.sex = sex;
this.age = age;
}
//设置工作经历
public void SetWorkExperience(string timeArea,string company){
this.timeArea = timeArea;
this.company = company;
}
//显示
public void Display(){
Console.WriteLine ("{0} {1} {2}", name, sex, age);
Console.WriteLine ("工作经历:{0} {1}", timeArea, company);
}
public Object Clone(){
return (Object)this.MemberwiseClone();
}
}
}
2.客户端代码
客户端代码
using System;
namespace Prototype
{
class MainClass
{
public static void Main (string[] args)
{
Resume resume1 = new Resume ("张三");
resume1.SetPersonalInfo ("男", "23");
resume1.SetWorkExperience ("1999-2002", "xx公司");
Resume resume2=(Resume)resume1.Clone();
resume2.SetWorkExperience ("2004-2005", "YY企业");
Resume resume3 = (Resume)resume1.Clone ();
resume3.SetPersonalInfo ("男", "24");
resume1.Display ();
resume2.Display ();
resume3.Display ();
}
}
}
3.运行结果
UML图
源码下载地址
http://blog.csdn.net/maybehelios/article/details/2038685