1.介绍
工厂方法模式是一种常用的类创建型设计模式,此模式的核心精神是封装类中变化的部分,
提取其中个性化善变的部分为独立类,通过依赖注入以达到解耦、复用和方便后期维护拓展的目的。
它的核心结构有四个角色,分别是抽象工厂;具体工厂;抽象产品;具体产品
2.示例
public class Human : IRace { public void ShowKing() { Console.WriteLine("The king of Human is Sky"); } }
public class NE : IRace { public void ShowKing() { Console.WriteLine("The king of NE is Moon"); } }
public class Orc : IRace { public void ShowKing() { Console.WriteLine("The king of Orc is Grubby"); } }
public class Undead : IRace { public void ShowKing() { Console.WriteLine("The king of Undead is Gostop"); } }
3.工厂方法接口
public interface IFactoryMethod { IRace CreateInstance(); }
public class HumanFactory : IFactoryMethod { public IRace CreateInstance() { return new Human(); } }
public class NEFactory : IFactoryMethod { public IRace CreateInstance() { return new NE(); } }
public class OrcFactory : IFactoryMethod { public IRace CreateInstance() { return new Orc(); } }
public class UndeadFactory : IFactoryMethod { public IRace CreateInstance() { return new Undead(); } }
class Program { static void Main(string[] args) { Human human2 = new Human(); human2.ShowKing(); //IRace human1 = new Human(); IFactoryMethod humanFactory = new HumanFactory(); IRace human = humanFactory.CreateInstance(); human.ShowKing(); Console.Read(); } }