using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Web;
using Northwind.IDAL;
namespace Northwind.DALFactory
{
    public class AbstractFactory
    {
        /// <summary>
        /// 抽象工厂，可以使用高速缓存提高性能
        /// </summary>
        /// <typeparam name="T">目标类型</typeparam>
        /// <param name="assemblyString">类所在的程序集名称</param>
        /// <param name="className">类的完全限定名称</param>
        /// <returns></returns>
        public static T Create<T>(string assemblyString, string className)
        {
            //return (T)Assembly.Load(assemblyString).CreateInstance(className);

            //缓存提高性能
            object objType = DataCache.GetCache(className);//从缓存读取
            if (objType == null)
            {
                try
                {
                    objType = Assembly.Load(assemblyString).CreateInstance(className);//反射创建
                    DataCache.SetCache(className, objType);// 写入缓存
                }
                catch
                { }
            }
            return (T)objType;
        }
    }

    public class DataCache
    {
        /// <summary>
        /// 获取当前应用程序指定CacheKey的Cache值
        /// </summary>
        /// <param name="CacheKey"></param>
        /// <returns></returns>
        public static object GetCache(string CacheKey)
        {
            System.Web.Caching.Cache objCache = HttpRuntime.Cache;
            return objCache[CacheKey];
        }

        /// <summary>
        /// 设置当前应用程序指定CacheKey的Cache值
        /// </summary>
        /// <param name="CacheKey"></param>
        /// <param name="objObject"></param>
        public static void SetCache(string CacheKey, object objObject)
        {
            System.Web.Caching.Cache objCache = HttpRuntime.Cache;
            objCache.Insert(CacheKey, objObject);
        }

    }
}
