四.原型模式实例分析(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 平台下实现克隆进行了描述。以一个实例进行了说明。原型模式是比较常用和简单的设计模式。