原型模式:从一个对象再创建另外一个可定制的对象,而且不需要知道任何创建的细节。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 原型模式
{
class Resume : ICloneable
{
private string name;
private string timeArea;
private string company;
public Resume(string name)
{
this.name = name;
}
public void setWork(string timeArea, string company)
{
this.timeArea = timeArea;
this.company = company;
}
public void Display()
{
Console.WriteLine("{0}",name);
Console.WriteLine("work is {0} {1}",timeArea,company);
}
public object Clone() //通过实现这个方法 实现原型模式
{
return (object)this.MemberwiseClone(); //如果类中的属性是值类型,则对该类的属性进行逐位复制,如果是引用类型,则复制引用
} 但不复制引用的对象,因此原始对象及其复本引用同一对象。这是浅表复制
}
class Program
{
static void Main(string[] args)
{
// Console.WriteLine("ni");
Resume a = new Resume("jia");
a.setWork("12","baidu");
a.Display();
Resume b = (Resume)a.Clone();
b.setWork("22","tengxu");
b.Display();
}
}
}
深复制
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 原型模式2
{
class Work : ICloneable //
{
private string t;
public string T
{
get { return t; }
set { t = value; }
}
public object Clone()
{
return (Object)this.MemberwiseClone();
}
}
class Resume : ICloneable
{
private string name;
private Work w;
public Resume(string name)
{
this.name = name;
}
private Resume(Work w) //
{
this.w = (Work)w.Clone();
}
public void setW(string t)
{
w.T = t;
}
public void Display()
{
Console.WriteLine("{0}",name);
Console.WriteLine("{0}",w.T);
}
public object Clone()
{
Resume obj = new Resume(this.w); //
obj.name = this.name;
return obj;
}
}
class Program
{
static void Main(string[] args)
{
Resume s = new Resume("jia");
s.setW("12");
Resume t = (Resume)s.Clone();
t.setW("13");
s.Display();
t.Display();
}
}
}