一、定义

原型模式:用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。

解释:有一个设计非常复杂的对象,如果需要得到多个这样对象的时候,可以先创建一个原型对象,然后使用原型对象clone出新的对象,从而实现减少内存消耗和类实例复用的目的。

 

二、UML类图及基本代码

设计模式(16)---原型模式

基本代码:

abstract class Prototype
    {
        private string id;
        public string ID
        {
            get { return id; }
        }

        public Prototype(string id)
        {
            this.id = id;
        }

        public abstract Prototype Clone();
    }

    class ConcretePrototype : Prototype
    {
        public ConcretePrototype(string id)
            : base(id)
        { }

        public override Prototype Clone()
        {
            return (Prototype)this.MemberwiseClone();
        }
    }

客户端调用:

ConcretePrototype cp1 = new ConcretePrototype("a");
            ConcretePrototype cp2 = (ConcretePrototype)cp1.Clone();

 

三、具体实例

编写一个简历,包含姓名、性别、年龄、工作经历等,然后复制多份进行显示。

实例代码及运行结果:

class Program
    {
        static void Main(string[] args)
        {
            Resume resume1 = new Resume("tom");
            resume1.SetPersonInfo("man", "17");
            resume1.SetWorkExperience("1980-1990", "xx company");

            Resume resume2 = (Resume)resume1.Clone();
            resume2.SetWorkExperience("1990-2000", "yy company");

            Resume resume3 = (Resume)resume1.Clone();
            resume3.SetPersonInfo("man", "19");

            resume1.Display();
            resume2.Display();
            resume3.Display();

            Console.Read();
        }
    }

    class Resume : ICloneable
    {
        private string name;
        private string sex;
        private string age;
        private string timeArea;
        private string company;

        public Resume(string name)
        {
            this.name = name;
        }

        public void SetPersonInfo(string sex, string age)
        {
            this.sex = sex;
            this.age = age;
        }

        public void SetWorkExperience(string timeArea, string company)
        {
            this.timeArea = timeArea;
            this.company = company;
        }

        public void Display()
        {
            Console.WriteLine("{0} {1} {2}", name, sex, age);
            Console.WriteLine("workexperience:{0} {1}", timeArea, company);
        }

        public object Clone()
        {
            return (object)this.MemberwiseClone();
        }
    }
View Code

相关文章:

  • 2021-11-20
  • 2021-11-20
  • 2021-08-08
  • 2021-09-24
猜你喜欢
  • 2022-01-08
  • 2021-07-05
  • 2021-11-10
  • 2022-12-23
  • 2022-12-23
  • 2021-12-12
  • 2021-11-20
相关资源
相似解决方案