Archive for the 'Design Pattern' Category
建立自己的消息循环
在MFC程序中使用消息机制的时候,常常会在程序即将完成的时候发现,在某个窗口中加入了太多的消息处理宏,并且这些消息的Handler和UI界面的方法混合在一起,待到项目规模大的时候,会导致后续的维护越来越困难。我们希望将UI的动作和业务处理的动作隔离开,互不影响,我们可以模仿MFC的消息流转机制,就本文来说,是Command的流转(Command Routing),大家知道,所有的从CCmdTarget派生的类都可以支持消息处理,比如CDocument, CView, CDocTemplate等。Framework在内部使用了Chain of Responsiblity。消息会在一个链条上找到自己的执行的地方,我们可以把不同的业务逻辑分割为各个不同的环,我们可以在修改一个环的情况下,而不去影响其他的环。附件中的例子只是简单的发送一个WM_COMMAND消息,消息的ID,表示了不同的动作。此方法适合发送消息时候,参数很少或者不用参数的情况。
示例代码的简单说明:
- 业务处理类需要从CCmdTarget派生
- 在每个业务处理类里面加入适当的消息映射(注意更新MyCommand.h中的消息的宏)
- 在CCmdManager类的BuildCmdTarget()中加入类的初始化
- 在主窗口的OnCmdMsg中调用 CCmdManager的CallOnCmdMsg方法
P.S.
这里写的只是MFC消息机制最粗糙的改造,由于时间的关系,这里不做过多的介绍
示例代码,点击这里下载
Here are some links about design pattern on the web
http://www.dofactory.com/Patterns/Patterns.aspx
http://home.earthlink.net/~huston2/dp/patterns.html
If you're new to Design Pattern, the links listed above may be helpful. the first one is easy to understand. it shows you the skeleton of every pattern and illustatues the details in real-world code. by the way, <<Head First Design Patter>> is also an amazing book for us, it's the best seller in many online bookshops recently.
Observer设计模式之软件语言的动态切换
随着网络的普及,软件的国际化问题,越来越值得让软件作者们多花些时间去思考。下面结合Observer模式,给出一个简单的多语言切换的例子。