原型模式 PrototypePattern

克隆模式实例
本文介绍了一个使用克隆模式创建对象的实例。通过定义一个原型接口IClone,并实现该接口的NiceGirl类,展示了如何利用克隆模式创建具有相同属性但独立的对象。此模式适用于需要大量复制对象而又不想让每个对象都占用大量内存的情况。

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(); } } }

调用者

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值