簡單工廠(Simple Factory Pattern)模式又叫靜態工廠方法模式(Static Factory Method Pattern)c#
經過一個工廠類的靜態方法建立若干類的實例。建立的這些類實例都有同一個父類,且這個父類是工廠類靜態方法的返回類型。如:ide
//基類 class static ClassBase { public static void Hello(); } class ClassA:ClassBase { public override void Hello() { Console.WriteLine("I am ClassA."); } } class ClassB:ClassBase { public override void Hello() { Console.WriteLine("I am ClassB"); } } class SimpleFactory { public static Create(string className) { classBase result = null; switch(className) { case "A": result = new ClassA();break; case "B": result = new ClassB();break; } return result; } } class Program { static void Main(string[] args) { ClassBase ca = SimpleFactory.Create("A"); ClassBase cb = SimpleFactory.Create("B"); ca.Hello(); cb.Hello(); Console.ReadLine(); } }