设计模式 - 7) 原型模式
发布日期:2021-05-13 19:47:06 浏览次数:26 分类:博客文章

本文共 2735 字,大约阅读时间需要 9 分钟。

������������������������������������������������������������������ Clone ������������������������������������������������������������������

1. ������

/// /// ���������������/// public abstract class Prototype{    public abstract Prototype Clone();}public class Companey{    public string Name { get; set; }    public string Place { get; set; }}/// /// ���������������/// public class Resume : Prototype{    public string Name { get; set; }        public Companey Com { get; set; }    public object Clone()    {        return (object)this.MemberwiseClone();    }    public void Show()    {        Console.WriteLine( string.Format("{0} ������������{1}", name, Com.Name + Com.Place));    }}Resume a = new Resume() { Name = "Mao", Com = new Companey() { Name = "Gxx", Place = "2819" } };Resume b = (Resume)a.Clone();Resume c = (Resume)a.Clone();a.Show();b.Show();c.Show();a.Name = "a";b.Name = "b";a.Show();b.Show();c.Show();

b���c ���������a��������������� a ��� Name ��� b���c ��������������������������� b ��� Name ������������������������������

Mao ���������Gxx2819Mao ���������Gxx2819Mao ���������Gxx2819a ���������Gxx2819b ���������Gxx2819Mao ���������Gxx2819

2. C# ��������� ICloneable

C# ������������ ICloneable ������������������������ Prototype ���������������������������

public class Resume : ICloneable { }

3. ���������������������

������ a ��� Name ������������������ string��������������������������� a ��� Name ��������� b���c ������������������������������������������ Com ������������������������������������

Resume a = new Resume() { Name = "Mao", Com = new Companey() { Name = "Gxx", Place = "2819" } };Resume b = (Resume)a.Clone();Resume c = (Resume)a.Clone();a.Show();b.Show();c.Show();a.Name = "a";a.Com.Place = "2866";b.Name = "b";b.Com.Place = "2828";a.Show();b.Show();c.Show();

���������

Mao ���������Gxx2819Mao ���������Gxx2819Mao ���������Gxx2819a ���������Gxx2828b ���������Gxx2828Mao ���������Gxx2828

������������������������ a ������������������������������������������������������������������������������������������������������������������.

4. ���������������

public class Companey : ICloneable{    public string Name { get; set; }    public string Place { get; set; }    public object Clone()    {        return (object)this.MemberwiseClone();    }}public class Resume : ICloneable{    ...        public Resume() { }    public Resume(Companey com)    {        this.Com = (Companey)com.Clone();    }    public object Clone()    {        Resume obj = new Resume(this.Com);        obj.Name = this.Name;        obj.Age = this.Age;        obj.Sex = this.Sex;        return obj;    }}

���������

Mao ���������Gxx2819Mao ���������Gxx2819Mao ���������Gxx2819a ���������Gxx2866b ���������Gxx2828Mao ���������Gxx2819
上一篇:设计模式 - 8) 模板模式
下一篇:设计模式 - 6) 工厂模式

发表评论

最新留言

表示我来过!
[***.240.166.169]2025年04月11日 10时43分58秒