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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值