前言:設計模式是軟件開發領域的精髓之一。學好設計模式是目前每一個開發人員的必修課。目前關于設計模式的書很多,其中比較好的有GOF那本的中譯本,但并不很適合初學者。還有一本是《JAVA與模式》,比較適合初學者使用,在此強烈推薦。但這本書的不足之處是一些地方講的過于繁瑣,很多地方只須簡單說明一下即可,卻大費筆墨,使得書籍很厚,看起來費力。而且是用JAVA描述的,這使得一些只懂C#的人無從下手。我是一個.net的擁護者,為了看這本書我特意看了些JAVA的書,感覺JAVA在書籍的多樣性方面比 .net好很多,而且不少書籍的質量很高。可能是現在JAVA已經比較成熟的原因吧。為了方便.net的愛好者學習設計模式,在此把我學習《JAVA與模式》這本書的學習筆記發出來,并用C#語言重新描述,希望能對初學者有所幫助。 其實設計模式也并不是什么高深的理論,個人認為并不是象一些人所說的“沒寫過10萬代碼就不要談設計模式”,只要用心學習與實踐是完全能夠掌握的。 簡單工廠模式是類的創建模式,又叫做靜態工廠方法模式。就是由一個工廠類根據傳入的參量決定創建出哪一種產品類的實例。一般涉及到三種角色(如下圖): 工廠類:擔任這個角色的是工廠方法模式的核心,含有與應用緊密相關的商業邏輯。工廠類在客戶端的直接調用下創建產品對象,它往往由一個具體的類實現。 抽象產品角色:擔任這個角色的類是由工廠方法模式所創建的對象的父類,或她們共同擁有的接口。一般由接口或抽象類實現。 具體產品角色:工廠方法模式所創建的任何對 象都是這個角色的實例,由具體類實現。
簡單工廠模式優缺點: 模式的核心是工廠類,這個類負責產品的創建,而客戶端可以免去產品創建的責任,這實現了責任的分割。但由于工廠類集中了所有產品創建邏輯的,如果不能正常工作的話會對系統造成很大的影響。如果增加新產品必須修改工廠角色的源碼。 以園丁種植水果為例討論該模式的具體實現: Fruit 水果接口,規定水果具有的一些共同特性 Apple 蘋果類 派生自Fruit接口 Strawberry 草莓類 派生自Fruit接口 FruitGardener 園丁類 負責草莓與蘋果的創建工作。 當Client要創建水果(蘋果或草莓對象)的時候調用園丁類的factory方法創建:UML圖如下:
代碼如下: Fruit.cs namespace Simple_Factory { public interface Fruit { //生長 void grow(); //收獲 void harvest(); //種植 void plant(); } } Apple.cs namespace Simple_Factory { public class Apple:Fruit { public Apple() { } #region Fruit 成員 public void grow() { Console.WriteLine ("Apple is growing......."); } public void harvest() { Console.WriteLine ("Apple is harvesting......."); } public void plant() { Console.WriteLine ("Apple is planting......."); } #endregion } } Strawberry.cs namespace Simple_Factory { public class Strawberry:Fruit { public Strawberry() { } #region Fruit 成員 public void grow() { Console.WriteLine ("Strawberry is growing......."); } public void harvest() { Console.WriteLine ("Strawberry is harvesting......."); } public void plant() { Console.WriteLine ("Strawberry is planting......."); } #endregion } } FruitGardener.cs namespace Simple_Factory { public class FruitGardener { //靜態工廠方法 public static Fruit factory(string which) { if(which.Equals ("Apple")) { return new Apple(); } else if(which.Equals ("Strawberry")) { return new Strawberry (); } else { return null; } } } } Client.cs using System; namespace Simple_Factory { class Client { [STAThread] static void Main(string[] args) { Fruit aFruit=FruitGardener.factory ("Apple");//creat apple aFruit.grow (); aFruit.harvest (); aFruit.plant(); aFruit=FruitGardener.factory ("Strawberry");//creat strawberry aFruit.grow (); aFruit.harvest (); aFruit.plant(); } } } 輸出如下: Apple is growing....... Apple is harvesting....... Apple is planting....... Strawberry is growing....... Strawberry is harvesting....... Strawberry is planting....
|