继续优化(如何才能避免产生大量子类的设计)
在上文中我使用协议表进行协议和协议处理函数的统一注册及管理,在开发原型的过程中发现一个问题:
呵呵,不好意思,这是我开发设计时的思考速记。发上来这个图也算是把自己的实践思考过程展示出来,让大家指点。
所以就像图上写的,二次开发协议的程序员将会定义很多函数名不同,但参数和返回值相同的函数。这不是很好~~
因此我将设计改为下面这种形式,我直接发代码了,绿色背景色标注的代码为新改进的。
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace DeviceSocket.Common.AnalyzeProtocol { using System.Reflection; /// <summary> /// 协议及处理函数注册表 /// </summary> public sealed class ProtocolTable { /// <summary> /// 协议表字典 /// </summary> private readonly static Dictionary<string, Delegate> DictTable = new Dictionary<string, Delegate>(); /// <summary> /// 协议表唯一实例 /// </summary> private static readonly ProtocolTable instance = new ProtocolTable(); public static ProtocolTable Instance { get { return instance; } } private ProtocolTable() { Init(); } /// <summary> /// 初始化协议表 /// </summary> private void Init() { DictTable.Add(ProtocolCommand.PRO_RESHEBEI_COMMAND, (typeof(Func<string, string>), GetMethod("RegisterDuKaQi"))); DictTable.Add(ProtocolCommand.PRO_CHECKSHEBEI_RESULT, (typeof(Func<string,int, string>), GetMethod("CheckDuKaQi"))); DictTable.Add(ProtocolCommand.PRO_YIQINAME_SYNC, (typeof(Action), GetMethod("TestVoidInvoke"))); } private MethodInfo GetMethod(string methodName) { } /// <summary> /// 根据协议执行协议处理函数 /// </summary> /// <param name="protocolCommand"></param> /// <param name="args"></param> /// <returns></returns> public object Do(string protocolCommand,) { if (!DictTable.ContainsKey(protocolCommand)) throw new ArgumentException("协议命令标识符不存在!"); MethodInfo methodInfo = DictTable[protocolCommand].Method; if (methodInfo != null && methodInfo.GetParameters().Count() <= 0) { return DictTable[protocolCommand].(); } return DictTable[protocolCommand].(args); } } }
//改进的地方基本思路就是使用Delegate 动态定义 加上DynamicInvoke,并且去掉了ProtocolArgs参数,改为params object[] args
改进后单元测试也全部通过,下一步我是打算
自动检索 ProtocolAnalyzeFunctionLib 并将其里面的函数注册到协议表字典中.(检索标准:带有自定义Attribute的方法)
呵呵 :) ,写的比较散,都是自己思考实践的过程。希望能给需要的朋友带来一些小小的参考吧。
转载于:https://www.cnblogs.com/guogai/archive/2011/07/07/2100532.html