如何打造属于自己的设计模式2015-03-16 cnblogs 熬夜的虫子设计模式 一般初级、中级、高级程序员都喜欢挂在嘴边的词。想必大家身边也有不少关于设计模式的书。设计模式是程序员的老前辈们根据自己的项目经验积累起来的解决方案集。所以,没必要把设计模式看成是硬性的东西,别人的经验参考一下即可,了解设计思路,为什么这种场景要用这种模式。也许是老一辈的程序员们确实比现在的程序员要强很多,毕竟现在网上很难找到自己摸索的设计模式了。虫子不才就先抛砖引玉了。简单介绍2个我项目中经常用到的模式1.机器人插件模式何所谓机器人插件,可以这样理解。你有一个机器人,但是需要这个机器人干什么并不确定。插入不同的卡片可以让机器人做出不同的行为。原理和aop类似,aop是站在系统级的角度,插件模式基于行为。直接看代码定义行为:
public static event EventHandler<RobotCancelEventArgs> DeleteingRobot;protected virtual void OnDeleteingRobot(RobotCancelEventArgs e){EventHandler<RobotCancelEventArgs> tmp = DeleteingRobot;if (tmp != null)tmp(this, e);}public static event EventHandler<RobotCancelEventArgs> bhingRobot;/// <summary>/// 机器人行动前触发事件/// </summary>protected virtual void OnbhingRobot(RobotCancelEventArgs e){EventHandler<RobotCancelEventArgs> tmp = bhingRobot;if (tmp != null)tmp(this, e);}public static event EventHandler<EventArgs> bhedRobot;/// <summary>/// 机器人行动后触发/// </summary>protected virtual void OnbhedRobot(EventArgs e){EventHandler<EventArgs> tmp = bhedRobot;if (tmp != null)tmp(this, e);}public static event EventHandler<ServingEventArgs> ServingRobot;/// <summary>/// 调用机器人行为时触发/// </summary>protected virtual void OnServing(ServingEventArgs e){EventHandler<ServingEventArgs> tmp = ServingRobot;if (tmp != null)tmp(this, e);}
行为实例:
public bool bhRobot(out string Message){Message = string.Empty;RobotCancelEventArgs e = new RobotCancelEventArgs();OnServing(e);if (!e.Cancel){var v = RobotService.bhRobot(this, out Message);if (v){OnbhedRobot(EventArgs.Empty);return true;}return false;}else{Message = e.Message;return false;}}
注册卡片:
[Extension("", "1.0", "熬夜的虫子")]public class CardRobot{static CardRobot(){Robot.ServingRobot += new EventHandler<ServingEventArgs>(Comment_ServingDelegate);}static void Comment_ServingDelegate(object sender, ServingEventArgs e){try{//do something}catch (Exception ex){//Log4N.WarnLog("BadWordFilterExtension Exception:", ex);}}}