定义一个用户创建对象的接口,让子类决定实例化哪一个
1.产品
interface IProduct { string ShipFrom(); } class ProductA : IProduct { public String ShipFrom () { return " from South Africa"; } } class ProductB : IProduct { public String ShipFrom () { return "from Spain"; } }
2.工厂
每个产品都有一个工厂
interface IProductFactory { IProduct FactoryMethod(); } class ProductFactoryA :IProductFactory { public IProduct FactoryMethod() { return new ProductA(); } } class ProductFactoryB : IProductFactory { public IProduct FactoryMethod() { return new ProductB(); } }
3.客户端调用
IProductFactory factory = new ProductFactoryA(); IProduct Product; Product = factory.FactoryMethod(); factory = new ProductFactoryB(); Product = factory.FactoryMethod();
与工厂模式比较,这里每个产品都有工厂,虽有扩展性,但每个产品都有工厂也造成了麻烦