public interface IClone { object Clone(); }
原型接口
using System; public class NiceGirl:IClone { private string _Name; private string _Tall; private string _SkinColor; private string _HairColor; private string _Weight; private string _Colthes; private string _Shoes; private string _Bag; public NiceGirl() { } private NiceGirl(NiceGirl nicegirl) { _Name = nicegirl.Name; _Tall = nicegirl.Tall; _SkinColor = nicegirl.SkinColor; _HairColor = nicegirl.HairColor; _Weight = nicegirl.Weight; _Colthes = nicegirl.Colthes; _Shoes = nicegirl.Shoes; _Bag = nicegirl.Bag; } public string Name { get { return _Name; } set { _Name = value; } } public string Tall { get { return _Tall; } set { _Tall = value; } } public string SkinColor { get { return _SkinColor; } set { _SkinColor = value; } } public string HairColor { get { return _HairColor; } set { _HairColor = value; } } public string Weight { get { return _Weight; } set { _Weight = value; } } public string Colthes { get { return _Colthes; } set { _Colthes = value; } } public string Shoes { get { return _Shoes; } set { _Shoes = value; } } public string Bag { get { return _Bag; } set { _Bag = value; } } public override string ToString() { string decorationList = string.Empty; decorationList += "Name:" + this.Name + "/n" + "Tall:" + this.Tall + "/n" + "SkinColor:" + this.SkinColor + "/n" + "HairColor:" + this.HairColor + "/n" + "Weight:" + this.Weight + "/n" + "Clothes:" + this.Colthes + "/n" + "Shoes:" + this.Shoes + "/n" + "Bag:" + this.Bag; return decorationList; } #region IClone 成员 public object Clone() { return new NiceGirl(this); } #endregion }
原型接口的实现者A
using System; using System.Collections.Generic; using System.Text; namespace PrototypePattern { class Program { static void Main(string[] args) { NiceGirl nicegirl = new NiceGirl(); nicegirl.Name = "露西"; nicegirl.Tall = "170CM"; nicegirl.Weight = "55KG"; nicegirl.SkinColor = "奶白色"; nicegirl.HairColor = "酒红色"; nicegirl.Shoes = "水晶色的低跟鞋"; nicegirl.Bag = "牛仔帆布袋"; Console.WriteLine("==========================One Girl====================================="); Console.WriteLine(nicegirl.ToString()); Console.WriteLine("==========================One Girl====================================="); NiceGirl nicegirl2 = nicegirl.Clone() as NiceGirl; Console.WriteLine("==========================Two Girl====================================="); Console.WriteLine(nicegirl2.ToString()); Console.WriteLine("==========================Two Girl====================================="); Console.ReadLine(); } } }
调用者
克隆模式实例
本文介绍了一个使用克隆模式创建对象的实例。通过定义一个原型接口IClone,并实现该接口的NiceGirl类,展示了如何利用克隆模式创建具有相同属性但独立的对象。此模式适用于需要大量复制对象而又不想让每个对象都占用大量内存的情况。
2109

被折叠的 条评论
为什么被折叠?



