设计模式学习总结(六)原型模式(Prototype)

设计模式学习总结(六)原型模式(Prototype)

  原型模式即通过对象拷贝的方式来实现对同类对象的生成的一种设计模式!

  浅复制:对于值类型,则直接复制该值,对于引用类型的字段则是对其引用的复制,如果原引用与现引用只要有一个的值发生变化,则都会造成两者值的变化。

    深复制:对于值类型,则直接复制该值,对于引用类型的字段则复制其引用的对象,如果有多个/级嵌套引用,则复制所有引用的对象。  

  一、示例展示:

  通过学习及总结,以下是我完成的原型模式的示例:

  1. 创建抽象原型类:HandphonePrototype

public abstract class HandphonePrototype
{
    private string cpu;
    private string keyboard;
    private string screen;

    public HandphonePrototype(string cpu,string keyboard,string screen)
    {
        this.cpu = cpu;
        this.keyboard = keyboard;
        this.screen = screen;
    }
    
    public string CPU
    {
        get
        {
            return cpu;
        }
    }

    public string KEYBOARD
    {
        get
        {
            return keyboard;
        }
    }

    public string SCREEN
    {
        get
        {
            return screen;
        }
    }
    abstract public HandphonePrototype Clone();
}
View Code

  2. 创建具体原型类:AppleHandphonePrototype

public class AppleHandphonePrototype : HandphonePrototype
{
    public AppleHandphonePrototype(string cpu, string keyboard, string screen) : base ( cpu,keyboard,screen ) { }
    public override HandphonePrototype Clone()
    {
        //Shallow copy
        return (HandphonePrototype)this.MemberwiseClone();
    }
}
View Code

  3. 客户端调用:

class Program
{
    static void Main(string[] args)
    {
        AppleHandphonePrototype cp1 = new AppleHandphonePrototype("100","26","Very wounderful!");
        AppleHandphonePrototype str = (AppleHandphonePrototype)cp1.Clone();
        Console.WriteLine(str.CPU);
        Console.WriteLine(str.KEYBOARD);
        Console.WriteLine(str.SCREEN);
        Console.ReadLine();
    }
}
View Code

  以上示例实现的是一个浅拷贝,如果希望实现一个深拷贝,则需要实现ICloneable接口并编写自己的Clone()方法;

  二、原型模式设计理念:

  以被拷贝对象作为原型,通过实现抽象原型类中的clone()方法在客户端进行对象的拷贝。主要通过浅拷贝(MemberwiseClone)和深拷贝(实现ICloneable接口并编写自己的克隆方法)来实现对对象引用和引用的对象的拷贝。

  三、角色及关系:

   设计模式学习总结(六)原型模式(Prototype) 

相关推荐