基於.net 職責鏈來實現 插件模式


    •   插件式的例子
  1.  QQ電腦管家,有很多工具列表,點一下工具下載后就可以開始使用了 
  2.  eclipse ,X Server 等等
    •   插件式的好處
  1. 插件降低框架的復雜性,把擴展功能從框架中剝離出來
  2. 讓第三方有機會來擴展程序的功能
    •   思路

      公開一個插件接口,如果.DLL或.EXE的代碼中有繼承這個接口就將其示為插件,並將這些插件放在同一目錄。運行程序的時候掃描目   錄並通過反射判斷.DLL或.EXE中是否存在該接口,若存在,則當作插件加載進來。如下圖示

         

  •   基於.net 職責鏈來實現 插件模式

          1.定義命令接口

           

     public interface ICommand
    {
        ServerReturn execute();

        ServerReturn Rollback();
    }

       獲取當前目錄下繼承該接口的方法

      

        public  List<ICommand> CommandList()
        {
            List<ICommand> ICommandList = new List<ICommand>();
            string[] files = Directory.GetFiles(System.IO.Directory.GetCurrentDirectory());
            int i = 0;

            foreach (string file in files)
            {
                string ext = file.Substring(file.LastIndexOf("."));
                if (ext != ".dll") continue;
                try
                {
                    // 加載插件
                    Assembly tmp = Assembly.LoadFile(file);
                    Type[] types = tmp.GetTypes();
                    bool ok = false;
                    foreach (Type t in types)
                        if (IsValidCommand(t))
                        {
                            // 通過反射實例化
                            ICommand plugin = (ICommand)tmp.CreateInstance(t.FullName);
                            ICommandList.Add(plugin);
                            ok = true;
                            if (ok) break;
                        }
                }
                catch (Exception err)
                {
                    throw err;
                }
            }

            return ICommandList;

        }


        /// <summary>
        /// 判斷DLL中是否繼承了ICommand接口
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        private static bool IsValidCommand(Type t)
        {
            bool ret = false;
            Type[] interfaces = t.GetInterfaces();
            foreach (Type theInterface in interfaces)
            {
                if (theInterface.FullName == "ClassDemo.ICommand")
                {
                    ret = true;
                    break;
                }
            }
            return ret;
        }

        職責鏈執行方法組

 

        /// <summary>
        /// 方法執行
        /// </summary>
        public void exec()
        {
            List<ICommand> list = new List<ICommand>();
            foreach( ICommand demo in list)
            {
                if(!demo.execute().isSurccess)
                {
                    demo.Rollback();
                    return;
                }
            }
        }

 


  

 

 

      

 

 

   


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM