📄 prototyperealworld.cs
字号:
using System;
using System.Windows.Forms;
using System.Collections;
//原型模式(Prototype)
//意图
// 用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。
//适用性
// 1.或者当要实例化的类是在运行时刻指定时,例如,通过动态装载;
// 2.或者为了避免创建一个与产品类层次平行的工厂类层次时;
// 3.或者当一个类的实例只能有几个不同状态组合中的一种时。
// 建立相应数目的原型并克隆它们可能比每次用合适的状态手工实例化该类更方便一些。
//例子
// CppUnit中在 Exception 的处理中,拷贝一个临时的异常对象并进行保存(TestCase::run(TestResult *result));
// catch ( Exception &e ) {
// Exception *copy = e.clone(); //clone 的方法通常是new一个和自身完全相同的对象
// result->addFailure( this, copy );
// }
namespace DesignPattern.PrototypeRealWorld
{
class PrototypeRealWorld : AbstractPattern
{
public static void Run(TextBox tbInfo)
{
s_tbInfo = tbInfo;
s_tbInfo.Text = "";
ColorManager colormanager = new ColorManager();
// Initialize with standard colors
colormanager["red" ] = new Color(255, 0, 0);
colormanager["green"] = new Color( 0, 255, 0);
colormanager["blue" ] = new Color( 0, 0, 255);
// User adds personalized colors
colormanager["angry"] = new Color(255, 54, 0);
colormanager["peace"] = new Color(128, 211, 128);
colormanager["flame"] = new Color(211, 34, 20);
Color color;
// User uses selected colors
string name = "red";
color = colormanager[name].Clone() as Color;
name = "peace";
color = colormanager[name].Clone() as Color;
name = "flame";
color = colormanager[name].Clone() as Color;
// Wait for user
//Console.Read();
}
}
// "Prototype"
abstract class ColorPrototype
{
public abstract ColorPrototype Clone();
}
// "ConcretePrototype"
class Color : ColorPrototype
{
private int red;
private int green;
private int blue;
// Constructor
public Color(int red, int green, int blue)
{
this.red = red;
this.green = green;
this.blue = blue;
}
// Create a shallow copy
public override ColorPrototype Clone()
{
DesignPattern.FormMain.OutputInfo( "Cloning color RGB: {0,3},{1,3},{2,3}", red, green, blue);
return this.MemberwiseClone() as ColorPrototype;
}
}
// Prototype manager
class ColorManager
{
Hashtable colors = new Hashtable();
// Indexer
public ColorPrototype this[string name]
{
get
{
return colors[name] as ColorPrototype;
}
set
{
colors.Add(name, value);
}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -