標籤:
- QQ電腦管家,有很多工具列表,點一下工具下載後就可以開始使用了
- eclipse ,X Server 等等
- 外掛程式降低架構的複雜性,把擴充功能從架構中剝離出來
- 讓第三方有機會來擴充程式的功能
公開一個外掛程式介面,如果.DLL或.EXE的代碼中有繼承這個介面就將其示為外掛程式,並將這些外掛程式放在同一目錄。運行程式的時候掃描目 錄並通過反射判斷.DLL或.EXE中是否存在該介面,若存在,則當作外掛程式載入進來。如示
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; } } }
基於.net 職責鏈來實現 外掛程式模式