一.抽象工廠模式:設計模式
在工廠模式中具體的產品和具體的工廠是一一對應的,一個工廠只能生產一種產品,結構單一,例如小米公司剛開始是隻生產小米手機,可是伴隨着公司的發展,他們須要生產不一樣型號的手機,也會生產路由器,小米電視等等,那麼工廠方法模式已不能知足業務的需求了,此時咱們就須要抽象工廠模式,即一個工廠能夠生產多種產品。ide
抽象產品:負責定義抽象工廠生成的產品的接口,在本例中有兩個抽象產品類,分別是手機和電視的抽象類測試
public abstract class IMobilePhone { public abstract void dial(); } public abstract class ITelevision { public abstract void watchTV(); }
public class MobilePhone : IMobilePhone { private string name; public MobilePhone(string name) { this.name = name; Console.WriteLine("製做手機"+name); } public override void dial() { Console.WriteLine("使用" + name+"打電話"); } } public class Television : ITelevision { private string name; public Television(string name) { this.name = name; Console.WriteLine("製做電視"+name); } public override void watchTV() { Console.WriteLine("經過"+name+"看電視"); } }
public abstract class Factory { public static Factory getFactory(string classname) { Factory factory = null; try { factory = (Factory)Assembly.Load("設計模式").CreateInstance("設計模式." + classname); } catch (Exception e) { Console.WriteLine("沒有找到 " + classname + "類。"); } return factory; } public abstract MobilePhone createMobilePhone(String type); public abstract Television createTelevision(String type); }
public class XiaoMiFactory:Factory { public override MobilePhone createMobilePhone(string type) { return new MobilePhone(type); } public override Television createTelevision(string type) { return new Television(type); } }
下面實際測試一下:this
static void Main(string[] args) { Factory factory = Factory.getFactory("XiaoMiFactory"); IMobilePhone mobilePhone1 = factory.createMobilePhone("小米2"); IMobilePhone mobilePhone2 = factory.createMobilePhone("小米5"); ITelevision television1 = factory.createTelevision("小米電視2"); ITelevision television2 = factory.createTelevision("小米電視3"); mobilePhone1.dial(); mobilePhone2.dial(); television1.watchTV(); television2.watchTV(); Console.ReadKey(); }
輸出信息:spa