美文网首页程序员IT@程序员猿媛程序园
设计模式- 原型模式(Prototype Pattern)

设计模式- 原型模式(Prototype Pattern)

作者: 易兒善 | 来源:发表于2019-04-26 09:46 被阅读1次

定义

原型模式(Prototype Pattern):指定使用原型实例创建的对象类型,并通过复制此原型创建新对象

C#例子

    [Serializable]
    public class Sheep : ICloneable
    {
        public string Name { get; set; }
        public List<Sheep> Children { get; set; }
        public Sheep(string name)
        {
            this.Name = name;
            Children = new List<Sheep>();
        }
        /// <summary>
        /// 通过ICloneable接口实现
        /// </summary>
        /// <returns></returns>
        public object Clone()
        {
            return new Sheep(Name);
        }
        /// <summary>
        /// MemberwiseClone 实现浅拷贝
        /// </summary>
        /// <returns></returns>
        public Sheep Clone1() 
        {
            return this.MemberwiseClone() as Sheep;
        }
        /// <summary>
        /// 二进制序列化实现深拷贝
        /// </summary>
        /// <returns></returns>
        public Sheep Clone2() {
            MemoryStream stream = new MemoryStream();
            BinaryFormatter formatter = new BinaryFormatter();
            formatter.Serialize(stream, this);
            stream.Position = 0;
            return formatter.Deserialize(stream) as Sheep;
        }
    }

原型模式参与者:

  • ICloneable:通过实现接口,自主选择新对象继承原来对象的属性。
  • MemberwiseClone:浅拷贝,拷贝值类型,引用类型和原来一样。
  • formatter:实现深拷贝,不仅仅拷贝了值类型,引用类型里的值也重新拷贝了一份。

原型模式适用情形

  • 当在运行时通过动态加载指定要实例化的类时
  • 当对象创建比克隆成本高时

原型模式特点

  • 它允许您创建一个现有对象的副本,并根据您的需要修改它,而不是经历从头创建和设置对象的麻烦。
  • 当一个类的实例只能有几个不同的状态组合中的一个时。安装相应数量的原型并克隆它们可能更方便,而不是每次以适当的状态手动实例化类。

其他

深拷贝

浅拷贝

源码地址

dotnet-design-patterns

其他设计模式

23种设计模式

相关文章

网友评论

    本文标题:设计模式- 原型模式(Prototype Pattern)

    本文链接:https://www.haomeiwen.com/subject/zsqggqtx.html