DataAccess类完全取代了前面创建的工厂类体系,它是一个sealed类,其中创建各种数据对象的方法,均为静态方法。之所以能用这个类达到抽象工厂的目的,是因为配置文件和反射的运用,如下的代码片断所示:
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"]; public static PetShop.IDAL.IOrder CreateOrder() { string className = orderPath + ".Order"; return (PetShop.IDAL.IOrder)Assembly.Load(orderPath).CreateInstance(className); } }
在PetShop中,这种依赖配置文件和反射创建对象的方式极其常见,包括IBLLStategy、CacheDependencyFactory等等。这些实现逻辑散布于整个PetShop系统中,在我看来,是可以在此基础上进行重构的。也就是说,我们可以为整个系统提供类似于“Service Locator”的实现:
public static class ServiceLocator { private static readonly string dalPath = ConfigurationManager.AppSettings["WebDAL"]; private static readonly string orderPath = ConfigurationManager.AppSettings["OrdersDAL"]; //…… private static readonly string orderStategyPath = ConfigurationManager.AppSettings["OrderStrategyAssembly"]; public static object LocateDALObject(string className) { string fullPath = dalPath + "." + className; return Assembly.Load(dalPath).CreateInstance(fullPath); } public static object LocateDALOrderObject(string className) { string fullPath = orderPath + "." + className; return Assembly.Load(orderPath).CreateInstance(fullPath); } public static object LocateOrderStrategyObject(string className) { string fullPath = orderStategyPath + "." + className; return Assembly.Load(orderStategyPath).CreateInstance(fullPath); } //…… }
那么和所谓“依赖注入”相关的代码都可以利用ServiceLocator来完成。例如类DataAccess就可以简化为:
public sealed class DataAccess { public static PetShop.IDAL.IOrder CreateOrder() { return (PetShop.IDAL.IOrder)ServiceLocator. LocateDALOrderObject("Order"); } }
通过ServiceLocator,将所有与配置文件相关的namespace值统一管理起来,这有利于各种动态创建对象的管理和未来的维护。
以上就是PetShop数据访问设计的全部内容,希望能给大家一个参考,也希望大家多多支持脚本之家。
您可能感兴趣的文章: