PetShop4.0是一个很好的源码学习工具,其内部提供了很多设计模式(Design Patterns)。这里介绍其中一种设计模式----抽象工厂模式

在PetShop中有下列的图关系的几个对象:

在WebConfig中定义了WebDAL和OrderDAL两个Keys:
<add key="WebDAL" value="PetShop.SQLServerDAL"/>
<add key="OrdersDAL" value="PetShop.SQLServerDAL"/>
当然也可以把值改成其他的,在PeeShop中可以选择SQLServerDAL和OracleDAL两种,因为其默认提供者两种。当然,有兴趣可以实现其他,例如DB2DAL之类的。这就是其的可扩展性。
在DALFactory中,可以看到如下代码:
……
namespace PetShop.DALFactory {

   
/// <summary>
    
/// DataAccess类实现了抽象工厂模式,例如在WebConfig中配置<add key="WebDAL" value="PetShop.SQLServerDAL"/>
    
/// 则工厂可以创建下列PetShop.SQLServerDAL里的Category、Inventory、Item、Order、Product等对象。
    
/// 注:PetShop中只提供两种选择,另一种为<add key="WebDAL" value="PetShop.OracleDAL"/>
    
/// </summary>

    public sealed class DataAccess {

        
// Look up the DAL implementation we should be using
        private static readonly string path = ConfigurationManager.AppSettings["WebDAL"];
        
private static readonly string orderPath = ConfigurationManager.AppSettings["OrdersDAL"];
        
        
private DataAccess() { }

        
public static PetShop.IDAL.ICategory CreateCategory() {
            
string className = path + ".Category";
            
return (PetShop.IDAL.ICategory)Assembly.Load(path).CreateInstance(className);
        }

            ……
    }

}
那么Client端就可以根据DALFactory来提供的对象来访问数据,把所有的对象都只用DALFactory这个窗口来提供。我们就可以通过这个窗口来查看“访问对象”这个世界。这样View变窄了,再多的对象也不会感觉复杂了。