經過工廠類提供的方法,建立不一樣的派生類git
一般建立的類都具備共同的基類/接口github
客戶端與具體的實現類解耦ide
新增產品須要修改原來工廠類的方法,不符合開閉原則code
public abstract class Phone { public abstract void Call(); }
public class IPhone : Phone { public override void Call() { System.Console.WriteLine("Call by IPhone"); } }
public class AndroidPhone : Phone { public override void Call() { System.Console.WriteLine("Call by Android"); } }
public static class PhoneFactory { public static Phone Create(string name) { switch (name) { case "IPhone": return new IPhone(); case "AndroidPhone": return new AndroidPhone(); default: throw new System.NotImplementedException($"未實現【{name}】類型"); } } }
var phone = PhoneFactory.Create("IPhone"); phone.Call(); phone = PhoneFactory.Create("AndroidPhone"); phone.Call();