C#抽象工厂简单实现类

曾经参与开发过的的项目,一般都是采用MVC模式进行开发,大概框架图如下:

web界面层调用BLL业务层,BLL通过抽象工厂DALFactory动态生成继承了IDAL的数据库操作层实例,以进行对数据库的各项操作。

DALFactory这层主要是根据web配置,通过反射动态生成IDAL实例,方便BLL层调用。

以前的做法是,IDAL每增加一个接口(如IUser),DALFactory就得添加一个方法用于产生继承了该接口的实例类.粗略代码:

 

 
  
public class DataAccess
{

protected static readonly string path = ConfigurationManager.AppSettings[ " ReportDemo_DAL " ];

public static IExcel_ReportCell CreateExcel_ReportCell()
{
string className = path + " . " + typeof (IExcel_ReportCell).Name.Substring( 1 );
return (IExcel_ReportCell)Assembly.Load(path).CreateInstance(className);
}

public static IExcel_Reportcondition CreateExcel_Reportcondition()
{
string className = path + " . " + typeof (IExcel_Reportcondition).Name.Substring( 1 );
return (IExcel_Reportcondition)Assembly.Load(path).CreateInstance(className);
}
// 更多....

}

这样就会有一个问题A:每添加一个接口就得创建一个工厂方法。感觉太麻烦了,于是对这个工厂进行了修改,代码如下:

 
  
1 using System.Reflection;
2   using System.Web;
3   using System.Web.Caching;
4   using System.Configuration;
5
6   namespace EHRExcelReprot.DALFactory
7 {
8 public sealed class ObjDataAccess < T >
9 {
10 // 获取web.confg文件配置信息
11   private static readonly string path = ConfigurationManager.AppSettings[ " ExcelReportDAL " ];
12 public static T Get()
13 {
14 // 注意:这里一定要确保这样一个命名规则:接口类名称只比继承它的类名称前面多一个‘I’字母
15 // 如:接口类名:IUser,继承它的类:User
16   string CacheKey = path + " . " + typeof (T).Name.Substring( 1 );
17 object objType = DataCache.GetCache(CacheKey); // 从缓存读取
18   if (objType == null )
19 {
20 try
21 {
22 objType = Assembly.Load(path).CreateInstance(CacheKey); // 反射创建
23 DataCache.SetCache(CacheKey, objType); // 写入缓存
24 }
25 catch
26 { }
27 }
28 return (T)objType;
29 }
30 }
31 /// <summary>
32 /// 缓存操作类
33 /// </summary>
34 public class DataCache
35 {
36 public static object GetCache( string CacheKey)
37 {
38 Cache objCache = HttpRuntime.Cache;
39 return objCache[CacheKey];
40 }
41
42 public static void SetCache( string CacheKey, object objObject)
43 {
44 Cache objCache = HttpRuntime.Cache;
45 objCache.Insert(CacheKey, objObject);
46 }
47 }
48 }

BLL层调用代码:

 
  
private static readonly IExcel_ReportInfo dal = ObjDataAccess < IExcel_ReportInfo > .Get();

这样就解决了上面的问题A。

本人菜鸟级别,希望得到各位大师的指点,谢谢。

 

 

 

 

 

 

转载于:https://www.cnblogs.com/252e/archive/2010/10/27/1862764.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值