千萬不要以為創(chuàng)建一個類,以Factory為后綴就是工廠,那不是工廠。
直接演示:
public interface IMachine { string Name { get; } /// <summary> /// 機器啟動 /// </summary> void TurnOn(); }
public class Computer : IMachine { public string Name { get { return "戴爾"; } } public void TurnOn() { Console.WriteLine("電腦啟動"); } } public class Mobile : IMachine { public string Name { get { return "魅族"; } } public void TurnOn() { Console.WriteLine("手機啟動"); } } public class UnknownMachine : IMachine { public string Name { get { return "機器故障" } } public void TurnOn() { Console.WriteLine("啟動失敗"); } }
class Program { static void Main(string[] args) { string description = "computer"; IMachine machine = GetMachine(description); machine.TurnOn(); Console.ReadKey(); } private static IMachine GetMachine(string description) { switch (description) { case "computer": return new Computer(); case "mobile": return new Mobile(); default: return new UnknownMachine(); } } }
上面代碼一執(zhí)行,IMachine接口里裝的Computer,所以電腦啟動了
工廠模式登場
public class MachineFactory { private Dictionary<string, Type> _machines; public MachineFactory() { LoadTypesICanReturn(); } public IMachine CreateInstance(string description) { Type t = GetTypeToCreate(description); if (t == null) return new UnknownMachine(); return Activator.CreateInstance(t) as IMachine; } private Type GetTypeToCreate(string machineName) { foreach (var machine in _machines) { if (machine.Key.Contains(machineName)) { return _machines[machine.Key]; } } return null; } private void LoadTypesICanReturn() { _machines = new Dictionary<string, Type>(); Type[] typesInThisAssembly = Assembly.GetExecutingAssembly().GetTypes(); foreach (Type type in typesInThisAssembly) { if (type.GetInterface(nameof(IMachine)) != null) { _machines.Add(type.Name, type); } } } }
static void Main(string[] args) { string description = "Computer"; IMachine machine = new MachineFactory().CreateInstance(description); machine.TurnOn(); Console.ReadKey(); }
CreateInstance方法也可以設計成靜態(tài)的
MachineFactory.CreateInstance(description);
在抽象一點可以讓MachineFactory實現(xiàn)IMachineFactory接口
public interface IMachineFactory { IMachine CreateInstance(string description); }
public class MachineFactory : IMachineFactory
static void Main(string[] args) { string description = "Computer"; IMachine machine = LoadFactory().CreateInstance(description); machine.TurnOn(); Console.ReadKey(); } private static IMachineFactory LoadFactory() { string factoryName = Properties.Settings.Default.DefaultMachineFactory; return Assembly.GetExecutingAssembly().CreateInstance(factoryName) as IMachineFactory; }
如果沒有上面的IMachineFactory接口,那么具體的工廠將與其生產(chǎn)的具體類型緊密耦合,我認為這也是可以接受的。好了。就是這么直截了當,簡單粗暴。
http://www.cnblogs.com/bidianqing/p/7188336.html