您的位置:首页 > 其它

【设计模式】之 Prototype 原型模式

2012-03-05 09:24 369 查看
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace DesignFactory.Prototype
{
/// <summary>
/// 原型模式
/// 类,通过实现ICloneable借口 可以实现Clone方法
/// </summary>
class Prototype
{
}

abstract class ColorPrototye
{
public abstract ColorPrototye Clone();

}

class Color : ColorPrototye
{
private int red, green, blue;
public Color(int red, int green, int blue)
{
this.red = red;
this.green = green;
this.blue = blue;
}

public override ColorPrototye Clone()
{
return (ColorPrototye)this.MemberwiseClone();
}

public void Display()
{
Console.WriteLine("RGB values are:{0},{1},{2}",red,green,blue);
}
}

class ColorManager
{
Hashtable colors = new Hashtable();

public ColorPrototye this[string name]
{

get { return (ColorPrototye)colors[name]; }
set { colors.Add(name,value); }
}

}

class PrototypeApp
{
public static void Main(string[] agrs)
{
ColorManager colormanager = new ColorManager();
colormanager["red"] = new Color(25, 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);

string colorName = "red";
Color c1 = (Color)colormanager[colorName].Clone();
c1.Display();
colorName = "peace";
Color c2 = (Color)colormanager[colorName].Clone();
c1.Display();
colorName = "flame";
Color c3 = (Color)colormanager[colorName].Clone();
c1.Display();
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: