原型模式,这个模式还是比较容易理解的,就是在类中添加一个方法用于复制自身一个新的对象,然后返回即可,由于这次是采用c#实现的原型模式,所以只需调用this.MemberwiseClone()即可实现自身的复制,但是这个仅仅是浅复制,值类型会进行复制,但是引用类型不复制引用对象,仅仅复制引用。
将c++和c#进行一下对比,两个最大的区别就是前者可以灵活使用指针,对内存的操作特别的方便,就比如说这个原型模式,c++只需在堆中重新分配一块内存存放自身即可。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 原型模式
{
class Program
{
static void Main(string[] args)
{
Resume res = new Resume("小明");
res.setpersonInfo("男", "20");
res.setworkExprience("2010-2012", "xx公司");
res.print();
Resume res2 = res.Clone();
res2.setpersonInfo("男", "22");
res2.setworkExprience("2013-2015", "yy公司");
res2.print();
Resume res3 = res.Clone();
res3.setpersonInfo("女", "24");
res3.setworkExprience("2016-2017", "zz公司");
res3.print();
}
}
}
class Resume
{
string name;
string sex;
string age;
string timeArea;
string company;
public Resume(string name)
{
this.name = name;
}
//设置个人信息
public void setpersonInfo(string sex, string age)
{
this.sex = sex;
this.age = age;
}
//设置工作经历
public void setworkExprience(string timeArea, string company)
{
this.timeArea = timeArea;
this.company = company;
}
//打印简历
public void print()
{
Console.WriteLine("{0} {1} {2}", name, sex, age);
Console.WriteLine("工作经历:{0} {1}", timeArea, company);
}
public Resume Clone()
{
return (Resume)this.MemberwiseClone();
}
}