0
点赞
收藏
分享

微信扫一扫

petshop中工厂模式中的应用


    petshop 4。0是个好东西,是个微软出的DEMO,里面用了了如工厂模式,策略模式,MSMQ和大量的asp.net 2.0新特性,
下面简要小结下其中的工厂模式的应用,可以在平常的项目中用到
    首先,petshop提供了sql server和oracle的实现类,其中的petshop.IDAL是访问的接口,其中用到了泛型,比如IProduct接口

public interface IProduct{

/// <summary>
/// Method to search products by category name
/// </summary>
/// <param name="category">Name of the category to search by</param>
/// <returns>Interface to Model Collection Generic of search results</returns>
IList<ProductInfo> GetProductsByCategory(string category); /// <summary>
/// Method to search products by a set of keyword
/// </summary>
/// <param name="keywords">An array of keywords to search by</param>
/// <returns>Interface to Model Collection Generic of search results</returns>
IList<ProductInfo> GetProductsBySearch(string[] keywords); /// <summary>
/// Query for a product
/// </summary>
/// <param name="productId">Product Id</param>
/// <returns>Interface to Model ProductInfo for requested product</returns>
ProductInfo GetProduct(string productId);
}


之后在SQLServerDAL中实现这些接口,这里就不说了,可以看代码。而数据访问工厂类是放在DALFactory包中的DataAccess类完成,其中代码为

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);
}


这里的ConfigurationManager.AppSettings["WebDAL"];
是在web.config文件中定义的,即
  <add key="WebDAL" value="PetShop.SQLServerDAL"/>,即指定实现类为采用SQL SERVER方式实现
     之后利用反射加载数据库访问处理类,同时创建接口实例,这里注意强制转型为Category类型的实例
   
    以上这个模式,可以用来在。NET中做工厂方法使用的一个例子和最佳实践



  

举报

相关推荐

0 条评论