BLLFactory的对象统一调用规则
在我的框架里面,所有的业务类调用都是以BLLFactory入口进行开始创建,传递业务对象进去即可创建,这种统一入口的方式能够方便记忆,并减少代码,更重要的是能够很好把一些如缓存规则、创建规则封装起来,简化代码。BLLFactory的创建示意图如下所示。
方法一:
using Globalegrow.Toolkit; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; namespace Globalegrow.BLL { /// <summary> /// 对业务类进行构造的工厂类 /// </summary> /// <typeparam name="T">业务对象类型</typeparam> public class BLLFactory<T> where T : class { private static Hashtable objCache = new Hashtable(); private static object syncRoot = new Object(); /// <summary> /// 创建或者从缓存中获取对应业务类的实例 /// </summary> public static T Instance { get { string CacheKey = typeof(T).FullName; T bll = (T)objCache[CacheKey]; if (bll == null) { lock (syncRoot) { if (bll == null) { Assembly assObj = Assembly.Load(typeof(T).Assembly.GetName().Name); object obj = assObj.CreateInstance(CacheKey); bll = obj as T; objCache.Add(typeof(T).FullName, bll); } } } return bll; } } } }
方法二:
using Globalegrow.Toolkit; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; namespace Globalegrow.BLL { /// <summary> /// 对业务类进行构造的工厂类 /// </summary> /// <typeparam name="T">业务对象类型</typeparam> public class BLLFactory<T> where T : class { private static object syncRoot = new Object(); /// <summary> /// /// </summary> public static T Instance { get { string CacheKey = typeof(T).FullName; lock (syncRoot) { T bll = Reflect<T>.Create(typeof(T).FullName, typeof(T).Assembly.GetName().Name); return bll; } } } } }
反射需要用到的扩展方法
using System.Collections; using System.Reflection; namespace Globalegrow.Toolkit { public class Reflect<T> where T : class { private static Hashtable m_objCache = null; public static Hashtable ObjCache { get { if (m_objCache == null) { m_objCache = new Hashtable(); } return m_objCache; } } public static T Create(string sName, string sFilePath) { return Create(sName, sFilePath, true); } public static T Create(string sName, string sFilePath, bool bCache) { string CacheKey = sFilePath + "." + sName; T objType = null; if (bCache) { objType = (T)ObjCache[CacheKey]; //从缓存读取 if (!ObjCache.ContainsKey(CacheKey)) { Assembly assObj = CreateAssembly(sFilePath); object obj = assObj.CreateInstance(typeof(T).FullName); objType = (T)obj; ObjCache.Add(CacheKey, objType);// 写入缓存 将DAL内某个对象装入缓存 } } else { objType = (T)CreateAssembly(sFilePath).CreateInstance(CacheKey); //反射创建 } return objType; } public static Assembly CreateAssembly(string sFilePath) { Assembly assObj = (Assembly)ObjCache[sFilePath]; if (assObj == null) { assObj = Assembly.Load(sFilePath); if (!ObjCache.ContainsKey(sFilePath)) { ObjCache.Add(sFilePath, assObj);//将整个ITDB。DAL。DLL装入缓存 } } return assObj; } } }
调用:
var systemConfigBLL = BLLFactory<SystemConfigBLL>.Instance.GetDBServiceTime();
时间: 2024-11-25 19:47:03