简单工厂模式有一个缺点,就是增加子类的时候,需要修改工厂类里的switch。工厂方法模式可以优化简单工厂模式的这个缺点。
UML图:
示例代码:
public interface ICar { string GuaDang(); }
public class ShouDong:ICar { public string GuaDang() { return "我是手动挡"; } }
public class ZiDong:ICar { public string GuaDang() { return "我是自动挡"; } }
public interface ICarFactory { ICar GetCar(); }
class ShouDongFactory:ICarFactory { public ICar GetCar() { return new ShouDong(); } }
public class ZiDongFactory:ICarFactory { public ICar GetCar() { return new ZiDong(); } }
class Program { static void Main(string[] args) { ICarFactory fac = new ShouDongFactory(); Console.WriteLine(fac.GetCar().GuaDang()); ICarFactory facA = new ZiDongFactory(); Console.WriteLine(facA.GetCar().GuaDang()); } }