千万不要以为创建一个类,以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(); } } }
上面代码一执行,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方法也可以设计成静态的
MachineFactory.CreateInstance(description);
在抽象一点可以让MachineFactory实现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接口,那么具体的工厂将与其生产的具体类型紧密耦合,我认为这也是可以接受的。好了。就是这么直截了当,简单粗暴。
时间: 2024-10-13 02:10:17