设计模式(六)——原型模式

原型模式(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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值