工厂方法中,每个工厂类,只完成单个实体的创建。抽象工厂方法可以优化此缺点。
UML图:
示例代码:
public interface ICar { string GuaDang(); }
public class ShouDong:ICar { public string GuaDang() { return "我是手动挡"; } }
public class ZiDong:ICar { public string GuaDang() { return "我是自动挡"; } }
public interface IPlane { string Fei(); }
public class ShouDongPlane:IPlane { public string Fei() { return "手动飞机起飞"; } }
public class ZiDongPlane:IPlane { public string Fei() { return "自动飞机起飞"; } }
public interface IFactory { ICar GetCar(); IPlane GetPlane(); }
class ShouDongFactory: IFactory { public ICar GetCar() { return new ShouDong(); } public IPlane GetPlane() { return new ShouDongPlane(); } }
public class ZiDongFactory : IFactory { public ICar GetCar() { return new ZiDong(); } public IPlane GetPlane() { return new ZiDongPlane(); } }
class Program { static void Main(string[] args) { IFactory fac = new ShouDongFactory(); Console.WriteLine(fac.GetCar().GuaDang()); Console.WriteLine(fac.GetPlane().Fei()); IFactory facA = new ZiDongFactory(); Console.WriteLine(facA.GetCar().GuaDang()); Console.WriteLine(facA.GetPlane().Fei()); } }