| Public interface IFruit { } public class Orange:IFruit { public Orange() { Console.WriteLine("An orange is got!"); } } public class Apple:IFruit { public Apple() { Console.WriteLine("An apple is got!"); } } |
| public class FruitFactory { public Orange MakeOrange() { return new Orange(); } public Apple MakeApple() { return new Apple(); } } |
| string FruitName = Console.ReadLine(); IFruit MyFruit = null; FruitFactory MyFruitFactory = new FruitFactory(); switch (FruitName) { case "Orange": MyFruit = MyFruitFactory.MakeOrange(); break; case "Apple": MyFruit = MyFruitFactory.MakeApple(); break; default: break; } |
| FruitFactory: public class FruitFactory { public IFruit MakeFruit(string Name) { switch (Name) { case "Orange": return new Orange(); case "Apple": return new Apple(); default: return null; } } } |
| string FruitName = Console.ReadLine(); IFruit MyFruit; FruitFactory MyFruitFactory = new FruitFactory(); MyFruit = MyFruitFactory.MakeFruit(FruitName); |
| public class FruitFactory { public IFruit MakeFruit(string Name) { IFruit MyFruit = null; try { Type type = Type.GetType(Name,true); MyFruit = (IFruit)Activator.CreateInstance(type); } catch (TypeLoadException e) Console.WriteLine("I dont know this kind of fruit,exception caught - {0}" ,e.Message); return MyFruit; } } |