关于设计模式,园子有太多的介绍了,我就不去摆文弄墨了。
关于工厂模式,算是最简单,最好理解的设计模式了,当然,可能是最多的设计模式了。我这里说的并不是这个模式的用法,或者见解,这是个人对于这个模式的一些用法的改进而已。
好了,入正题。想必,可能大多数人写工厂模式的代码都是如此。但是,如果再增加一个IPlant的类,就必须地增加if条件判断。对于我这种对代码有洁癖的人,实在受不了。
namespace FactoryMode{ class Program { static void Main(string[] args) { var plant = PlantFactory.GetPlant("Jd"); } } public interface IPlant { void DownLoad(); void SendBackMsg(); } public class PlantFactory { public static IPlant GetPlant(string plantName) { if (plantName == "Jd") return new JdPlant(); if (plantName == "Tb") return new TbPlant(); else return null; } } public class JdPlant : IPlant { public void DownLoad() { Console.WriteLine("Jd_DownLoad"); //throw new NotImplementedException(); } public void SendBackMsg() { Console.WriteLine("Jd_SendBackMsg"); //throw new NotImplementedException(); } } public class TbPlant : IPlant { public void DownLoad() { Console.WriteLine("Tb_DownLoad"); //throw new NotImplementedException(); } public void SendBackMsg() { Console.WriteLine("Tb_SendBackMsg"); //throw new NotImplementedException(); } }} 改进后的代码:
namespace FactoryMode{ class Program { static void Main(string[] args) { var plant = PlantFactory.GetPlant("Jd"); } } public interface IPlant { void DownLoad(); void SendBackMsg(); } public class PlantFactory { private static DictionaryplantDictionary = new Dictionary (); public PlantFactory() { plantDictionary.Add("Jd", typeof(JdPlant)); plantDictionary.Add("Tb", typeof(TbPlant)); } public static IPlant GetPlant(string plantName) { IPlant plant = null; if (plantDictionary.Keys.Contains(plantName)) { plant = (IPlant)Activator.CreateInstance(plantDictionary[plantName]); } return plant; } } public class JdPlant : IPlant { public void DownLoad() { Console.WriteLine("Jd_DownLoad"); //throw new NotImplementedException(); } public void SendBackMsg() { Console.WriteLine("Jd_SendBackMsg"); //throw new NotImplementedException(); } } public class TbPlant : IPlant { public void DownLoad() { Console.WriteLine("Tb_DownLoad"); //throw new NotImplementedException(); } public void SendBackMsg() { Console.WriteLine("Tb_SendBackMsg"); //throw new NotImplementedException(); } }}