• C#抽象工厂简单实现类 no


    曾经参与开发过的的项目,一般都是采用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。

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

  • 相关阅读:
    Java内存模型(JMM)
    线程安全问题的本质详解: 原子性、有序性、可见性
    Quartz实现分布式可动态配置的定时任务
    Java引用详解-StrongReference SoftReference WeakReference PhantomReference
    流行的报表生成工具-JXLS
    Java线程监控及中断
    IntelliJ IDEA 内存优化最佳实践
    Dapeng框架-开源高性能分布式微服务框架
    Scala实现Try with resources自动关闭IO
    Jvm启动,关闭及对应钩子
  • 原文地址:https://www.cnblogs.com/252e/p/1862764.html
Copyright © 2020-2023  润新知