C# 设计模式6 原型(Prototype)

参考:head first 设计模式

应用场景

对象的克隆,复制。有一个对象了,通过对它的复制来创建一个相同或类似的新对象。
如细胞分裂,1分2,2分4,再无限分。

结构

1.通过ICloneable接口来实现,或者搞一个抽象类。.net中用前者好些。
2.抽象类的方式如下:
原型:Prototype
具体原型类:ConcretePrototype 可以复制的对象继承自Prototype
客户端调用:PrototypeClient来调用上面的Clone来创建对象

图例

在这里插入图片描述

特点

优点:
向客户隐藏创建的复杂性,可以动态的增加或减少产品类。适用于任何结构,无须先确定产品的等级结构。
缺点:
每个类必须有克隆的方法,有循环结构的对象的话会麻烦。

系统自带

ICloneable

代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DesignPattern
{
    public class PrototypeClient
    {
        public static void main()
        {
            //方式1
            Prototype ptype = new ConcretePrototype("abstracttype", "abstract");
            Prototype pt1 = ptype.Clone();
            Console.WriteLine(pt1.Name);

            Prototype pt2 = ptype.Clone();
            Console.WriteLine(pt2.Name);
            Console.WriteLine(pt1.Equals(pt2));//false hashcode不同  referernce不同 内存地址不同

            //方式2
            ConcretePrototypeInterface pti1 = new ConcretePrototypeInterface();
            pti1.Name = "prototype interface";
            pti1.Type  ="interface";
            ConcretePrototypeInterface pti2 = pti1.Clone() as ConcretePrototypeInterface;
            Console.WriteLine(pti1.Equals(pti2));//true 如果没有重写Equals仍为false 
            Console.WriteLine(ReferenceEquals(pti1, pti2));//false 
        }
    }

    /// <summary>
    /// 抽象原型
    /// </summary>
    public abstract class Prototype
    {
        public string Name { get; set; }
        public string Type { get; set; }

        public Prototype(string id, string type)
        {
            this.Name = id;
            this.Type = type;
        }

        //克隆
        public abstract Prototype Clone();
    }

    /// <summary>
    /// 具体原型对象
    /// </summary>
    public class ConcretePrototype : Prototype
    {
        public ConcretePrototype(string name, string type) : base(name, type)
        {

        }

        //浅拷贝,只拷贝值,不拷贝引用; 深拷贝需要拷贝引用
        public override Prototype Clone()
        {
            return (Prototype)this.MemberwiseClone();
        }
    }

    public class ConcretePrototypeInterface : ICloneable,IEquatable<ConcretePrototypeInterface>
    {
        public string Name { get; set; }
        public string Type { get; set; }
        public object Clone()
        {
            return new ConcretePrototypeInterface() { Name = this.Name, Type = this.Type };
        }

        public bool Equals(ConcretePrototypeInterface other)
        {
            return this.Name.Equals(other.Name) && this.Type.Equals(other.Type);
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值