public ConcteteColorPrototype(ConcteteColorPrototype o) { this._red = o._red; this._green = o._green; this._blue = o._blue; this._apha = o._apha; }
static void test_prototype_mode() { /* * 原型模式:用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。 * 设计原则 - 1、依赖倒置原则 * 适用范围: * 1、当要实例化的类是在运行时刻指定时,例如,通过动态装载; * 2、为了避免创建一个与产品类层次平行的工厂类层次时; * 3、当一个类的实例只能有几个不同状态组合中的一种时。建立相应数目的原型并克隆它们可能比每次用合适的状态手工实例化该类更方便一些。 */ Console.WriteLine("\n---------------- test proxy --------------------\n"); ColorManager colormanager = new ColorManager(); string[] colorname = { "red", "green" , "blue" }; colormanager[colorname[0]] = new ConcteteColorPrototype(255, 0, 0, 0); colormanager[colorname[1]] = new ConcteteColorPrototype(0, 255, 0, 0); colormanager[colorname[2]] = new ConcteteColorPrototype(0, 0, 255, 0); ConcteteColorPrototype c0 = (ConcteteColorPrototype)colormanager[colorname[0]].clone(false); ConcteteColorPrototype c1 = (ConcteteColorPrototype)colormanager[colorname[1]].clone(false); ConcteteColorPrototype c2 = (ConcteteColorPrototype)colormanager[colorname[2]].clone(false); c0.Display(colorname[0]); c1.Display(colorname[1]); c2.Display(colorname[2]); }
public ColorPrototype createDeepCopy(bool isSerial) { ColorPrototype colorPrototype = null; if (isSerial) { /* * 此处使用序列化实现深拷贝。 * 序列化就是指将对象实例以二进制流的形式保存下来(文件保存、发送给网络), * 这些二进制流再通过反序列化,将序列化的对象加载到程序中 */ MemoryStream memoryStream = new MemoryStream(); BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(memoryStream, this);//序列化ColorPrototype对象 memoryStream.Position = 0; colorPrototype = (ColorPrototype)formatter.Deserialize(memoryStream);//反序列化出ColorPrototype对象 } else { //此处实现深拷贝 colorPrototype = new ConcteteColorPrototype(this); } return colorPrototype; }