DotNet个性化实现工厂类DLL缓存

来源:互联网 发布:puppy linux 编辑:程序博客网 时间:2024/06/15 06:25


通过appconfig配置文件实现一种工厂设计模式

using System;using System.Collections.Generic;using System.Text;using System.Configuration;using System.Reflection;namespace ConsoleApplication1{    class TestFactoryFromAppConfig    {        /// <summary>        /// 个性化实现工厂类DLL缓存        /// </summary>        private static Dictionary<string, Assembly> _FactoryDllCach = new Dictionary<string, Assembly>();        public static void Main()         {            TestFactoryFromAppConfig tfac = new TestFactoryFromAppConfig();            Interface ife = (Interface)tfac.GetFactoryClass("SamTestForFactory");            ife.SayHello();            Console.Read();        }    private object GetFactoryClass(string p)    {      /// <summary>        /// 获取个性化实现工厂类        /// </summary>            object actionObj = null;            string vValue = ConfigurationManager.AppSettings[p];            string[] typeList = vValue.Split(',');            try            {                System.Reflection.Assembly dll = null;                if (_FactoryDllCach.ContainsKey(p))                {                    dll = _FactoryDllCach[p];                }                else                {                    dll = Assembly.Load(typeList[1].Trim());                    _FactoryDllCach.Add(p, dll);                }                actionObj = dll.CreateInstance(typeList[0].Trim());            }            catch (Exception ex)            {                throw new Exception("加载实现类出错!", ex);            }            return actionObj;        }    }}

工厂实现类代码如下,其实现了接口中的某某方法:

using System;using System.Collections.Generic;using System.Text;namespace ConsoleApplication1.ChildFolder{    class Child : Interface    {        #region Interface 成员        public void SayHello()        {            string teacher = "teacher";            Console.WriteLine("hellow {0}", teacher);        }        #endregion    }}

接口定义SayHello方法:

using System;using System.Collections.Generic;using System.Text;namespace ConsoleApplication1{    public interface Interface    {        void SayHello();    }}
appconfig配置文件定义了一个键值对,通过  ConfigurationManager.AppSettings方法获取值。

<?xml version="1.0" encoding="utf-8" ?><configuration>  <appSettings>        <add key="SamTestForFactory" value="ConsoleApplication1.ChildFolder.Child,ConsoleApplication1"/>    </appSettings></configuration>


把程序集放入缓存中,如果下次访问的仍然是同一个键,则无需再次装载程序集,从缓存中读取即可。

原创粉丝点击