因为生产各个不同产品的工序不同,所以各自的MakeProduct方法也不同
public class ProductA : Product { public override string MakeProduct() { return " You has made a ProductA " ; } } public class ProductB : Product { public override string MakeProduct() { return " You has made a ProductB " ; } } public class ProductC : Product { public override string MakeProduct() { return " You has made a ProductC " ; } }现在有这样一个场景,这个工厂一天会生产一个产品,实现的代码很简单,例如今天生产A
ProductA objA = new ProductA() objA.MakeProduct();但是明天这个厂又生产B了,我们就得修改代码,于是就需要有一个类,根据配置来生成不同的实体。
public class SimplyFactory { private SimplyFactory() { } public static Product GetInstance( string productType) { switch (productType.ToUpper()) { case " A " : return new ProductA(); case " B " : return new ProductB(); case " C " : return new ProductC(); default : throw new Exception( " We don't have this product line " ); } } }这样我们就能不修改任何代码,只修改配置文件,就可以生产不同的产品了
Product product = SimplyFactory.GetInstance( " B " ); string strProductResult = product.MakeProduct(); MessageBox.Show(strProductResult);
总结一下简单工厂模式适合的场景:
一批对象,具有相同的行为 外部只用关心这一行为,而不用关心这一行为的具体实现 通过配置,可以控制这一行为在看一下实际开发中常常会用到简单工厂的地方:
数据库连接我们可能会连到不同的数据源,如:SQLServer,Oracle等,他们都有Open和Close行为,我们需要通过配置来决定到底使用哪个连接,这时可使用简单工厂。 FTP/SFTP切换同样都有共同行为upload,download,需要通过配置决定到底使用哪个方法,这时也可使用简单工厂