原型模式
1 普通克隆
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Clone
{
class Program
{
abstract class property
{
public abstract property Clone();
}
class ConcreatProperty:property
{
private string str;
public string Str
{
get
{
return str;
}
set
{
str = value;
}
}
public override property Clone()
{
ConcreatProperty mm = new ConcreatProperty();
mm.Str = str;
return mm;
}
}
static void Main(string[] args)
{
ConcreatProperty mm = new ConcreatProperty();
mm.Str = "我是MM";
ConcreatProperty nn = mm.Clone() as ConcreatProperty;
Console.WriteLine(nn.Str);
Console.ReadKey();
}
}
}
MemberwiseClone克隆()
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Clone
{
class Program
{
abstract class property
{
public abstract property Clone();
}
class ConcreatProperty:property
{
private string str;
public string Str
{
get
{
return str;
}
set
{
str = value;
}
}
public override property Clone()
{
return this.MemberwiseClone() as property;
}
}
static void Main(string[] args)
{
ConcreatProperty mm = new ConcreatProperty();
mm.Str = "我是MM";
ConcreatProperty nn = mm.Clone() as ConcreatProperty;
Console.WriteLine(nn.Str);
Console.WriteLine(nn == mm);
Console.WriteLine(nn.Str == mm.Str);
Console.ReadKey();
}
}
}
应用基类ICloneable -深克隆
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Clone
{
class Program
{
abstract class property
{
public abstract property Clone();
}
class ConcreatProperty:ICloneable
{
private string str;
public string Str
{
get
{
return str;
}
set
{
str = value;
}
}
public object Clone()
{
ConcreatProperty mm= this.MemberwiseClone() as ConcreatProperty;
mm.Str = "我是深克隆";
return mm;
}
}
static void Main(string[] args)
{
ConcreatProperty mm = new ConcreatProperty();
mm.Str = "我是原型";
ConcreatProperty nn = mm.Clone() as ConcreatProperty;
Console.WriteLine(mm.Str);
Console.WriteLine(nn.Str);
Console.WriteLine(nn == mm);
Console.WriteLine(nn.Str == mm.Str);
Console.ReadKey();
}
}
}