Net设计模式实例之原型模式( Prototype Pattern)(2)

四.原型模式实例分析(Example

1、场景

颜色索引器存储多种颜色值,从颜色索引器中克隆客户需要几种颜色。结构 如下图所示 <?XML:NAMESPACE PREFIX = O />

 

ColorManager :颜色索引器

ColorPrototype :原型模式抽象类

Color :原型模式抽象类的具体实现, Clone 方法的实现,克隆自身的操作

2、代码

1 原型模式抽象类ColorPrototype 及其具体实现类Color

/// <summary>

/// 原型模式抽象类

/// </summary>

public abstract class ColorPrototype

{

    public abstract ColorPrototype Clone();

}

/// <summary>

/// 具体实现类

/// </summary>

public class Color : ColorPrototype

{

    private int _red;

    private int _green;

    private int _blue;

 

    public Color(int red, int green, int blue)

    {

        this ._red = red;

        this ._green = green;

        this ._blue = blue;

    }

    /// <summary>

    /// 实现浅复制

    /// </summary>

    /// <returns></returns>

    public override ColorPrototype Clone()

    {

        Console .WriteLine("Cloning color RGB: {0,3},{1,3},{2,3}" , _red, _green, _blue);

        return this .MemberwiseClone() as ColorPrototype ;

    }

}

 

3 、客户端代码

static void <?XML:NAMESPACE PREFIX = ST1 />Main (string [] args)

{

    ColorManager colormanager = new ColorManager ();

 

    // 初始化标准的red green blue 颜色。

    colormanager["red" ] = new Color (255, 0, 0);

    colormanager["green" ] = new Color (0, 255, 0);

    colormanager["blue" ] = new Color (0, 0, 255);

 

    // 添加个性的颜色

    colormanager["angry" ] = new Color (255, 54, 0);

    colormanager["peace" ] = new Color (128, 211, 128);

    colormanager["flame" ] = new Color (211, 34, 20);

 

    // 克隆颜色

    Color color1 = colormanager["red" ].Clone() as Color ;

    Color color2 = colormanager["peace" ].Clone() as Color ;

    Color color3 = colormanager["flame" ].Clone() as Color ;

 

    Console .ReadKey();

}

3、实例运行结果

五、总结(Summary

本文对原型模式( Prototype Pattern )的概念、设计结构图、代码、使用场景、深复制与浅复制的区别,以及如何 Net 平台下实现克隆进行了描述。以一个实例进行了说明。原型模式是比较常用和简单的设计模式。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值