文章出處
文章列表
原型模式是創建型模式的一種,其特點在于通過“復制”一個已經存在的實例來返回新的實例(clone),而不是新建(new)實例。被復制的實例就是我們所稱的“原型”,這個原型是可定制的。
原型模式多用于創建復雜的或者耗時的實例,因為這種情況下,復制一個已經存在的實例使程序運行更高效;或者創建值相等,只是命名不一樣的同類數據。
從原型模式的概念中,我們可以看到,在這個模式里,拷貝是個很重要的概念,即在不創建對象的情況下,返回一個已有對象,這就是拷貝去實現的,在面向對象的編程世界里,拷貝分為淺拷貝和深拷貝,如果希望對兩者有更深入的認識,
可以閱讀我的這篇文章《不忘本~淺拷貝和深拷貝》。
何時能用到它?
當你一個大對象被創建后,它可以在程序里被使用多次,而使用的時候可能有些屬性值會發生變化,這里,你不需要重新去new這個對象,而可以使用原型模式去克隆這個對象,這樣,可以提交程序的性能。
策略模式的結構圖
策略模式實現說明
CarPrototype:抽象原型,定義一個克隆的方法,返回規定的原型
ConcteteCarPrototype:具體原型,實現了抽象原來的克隆,并返回了這類抽象原型,在具體原型中,還提供了某體的屬性和方法等
CarManagerL:原型管理器,這個管理員用于被前臺(UI)去調用,它用來存儲原型集合
策略模式的C#實現
#region 原型模式 abstract class CarPrototype { public abstract CarPrototype Clone(); } class ConcteteCarPrototype : CarPrototype { private string _body, _color, _wheal; public ConcteteCarPrototype(string body, string color, string wheal) { this._body = body; this._color = color; this._wheal = wheal; } public override CarPrototype Clone() { //實現淺表拷貝 return (CarPrototype)this.MemberwiseClone(); } public void Display(string _carName) { Console.WriteLine("{0}'s Cart Values are: {1},{2},{3}", _carName, _body, _color, _wheal); } } class CarManager { Hashtable colors = new Hashtable(); public CarPrototype this[string name] { get { return (CarPrototype)colors[name]; } set { colors.Add(name, value); } } } #endregion
調用代碼
CarManager colormanager = new CarManager(); //初始化 colormanager["奧迪"] = new ConcteteCarPrototype("德國", "黑色", "四輪驅動"); colormanager["奇端"] = new ConcteteCarPrototype("中國", "白色", "前輪驅動"); //調用 ConcteteCarPrototype c1 = (ConcteteCarPrototype)colormanager["奇端"].Clone(); c1.Display("奇端"); Console.ReadLine();
結果截圖
文章列表
全站熱搜