C# 设计模式(3)工厂方法模式
1. 基于开闭原则 OCP: 对扩展开放,对修改封闭。
2. 基于单一原则
代码实现:WarCraft3 服务
namespace FactoryMethod.Warcraft3Service { public interface IRace { void InterWar(); } public class Human:IRace { public void InterWar() { Console.WriteLine($"I'm Sky, using Human"); } } public class NE:IRace { public void InterWar() { Console.WriteLine($"I'm Moon, using NE"); } } }
工厂方法:
namespace FactoryMethodPattern.FactoryMethod { public interface IRaceFactory { IRace GetInstance(); } public class HumanFactory: IRaceFactory { public IRace GetInstance() { IRace race = new Human(); return race; } } public class NEFactory:IRaceFactory { public virtual IRace GetInstance() { IRace race = new NE(); return race; } } public class SuperNEFactory : NEFactory { public override IRace GetInstance() { return base.GetInstance(); } } }
调用工厂:
class Program { static void Main(string[] args) { IRaceFactory humanFactory = new HumanFactory(); humanFactory.GetInstance().InterWar(); IRaceFactory superNeFactory = new SuperNEFactory(); superNeFactory.GetInstance().InterWar(); } }
结果: