Design Pattern :Prototype

来源:互联网 发布:如何恢复航天开票数据 编辑:程序博客网 时间:2024/06/05 16:44

一定义、能过给出一个原型对象来指明所要创建的对象类型,然后用复制这个原型对象的方法创建出更多同类型的对象;


二UML类图 如下所示:





三模试角色与结构:

1、Prototype声明所要复制的原型

2、ConcretePrototype实现复制原型的Clone方法

3、Client通过调用Prototype的Clone方法复制对象


四程序举例:

使用原型模式。创建书的对象,书对象包含有“书名”“作者”“出版社”“印刷信息”。其中“印刷信息”是一个类成员,“印刷信息”的成员有“印刷日期”,“印刷份数”等。采用深复制方式,创建一个书的副本,并修改副本的信息,分别显示出“原型”和“副本”的信息。






using System; using System.Collections.Generic; using System.Linq; using System.Text;  namespace Prototype {      public class Publish      {          private DateTime date;          public DateTime Date         {             get { return date; }             set { date = value; }         }         private int count;          public int Count         {             get { return count; }             set { count = value; }         }           public Publish Clone()         {             return (Prototype.Publish)this.MemberwiseClone();         }     }       public class Book : ICloneable     {          public Book()         {             p = new Publish();         }          private string bookname;          public string Bookname         {             get { return bookname; }             set { bookname = value; }         }         private string author;          public string Author         {             get { return author; }             set { author = value; }         }         private string publisher;          public string Publisher         {             get { return publisher; }             set { publisher = value; }         }         private Publish p;          internal Publish P         {             get { return p; }             set { p = value; }         }           public object Clone()         {             Book b = (Prototype.Book)this.MemberwiseClone();             b.P = this.P.Clone();             return b;         }     }      class Client     {         static void Main(string[] args)         {              Book b1 = new Book();             b1.Bookname = "Java";             b1.Author = "zs";             b1.Publisher = "China";             b1.P.Count = 10000;             b1.P.Date = System.DateTime.Now;              Book b2 = (Book)b1.Clone();             b2.Bookname = "C#";             b2.P.Count = 20000;              Console.WriteLine("{0},{1},{2},{3},{4}",b1.Bookname,b1.Author,b1.Publisher,b1.P.Date,b1.P.Count);             Console.WriteLine("{0},{1},{2},{3},{4}", b2.Bookname, b2.Author, b2.Publisher, b2.P.Date, b2.P.Count);          }     } } 

结果为:


原创粉丝点击