对回调函数进行简单封装
2009-05-20 22:30
344 查看
封装的原则很简单,子类通过继承基类的一个虚方法,将回调转到子类的成员函数里面,从而可以使用子类成员函数的一些私有方法和成员。
// ---- code
// .h
// .CPP
// 使用
KCBDoWith cbDoWith;
KCBDoWith::CBFunc(&cbDoWith, 2);
[END]
// ---- code
// .h
#ifndef __KCBBASE_H__ #define __KCBBASE_H__ // ------------------------------------------------------------------------- class KCBBase { public: static bool CBFunc(void *pData, unsigned int uMsg) { KCBBase *pThisObject = (KCBBase *) pData ; return pThisObject->Function(uMsg); } virtual bool Function(unsigned int nMsg){return true;}; protected: }; class KCBWork : public KCBBase { public: bool Function(unsigned int nMsg); bool SubFunc_1(); bool SubFunc_2(); bool SubFunc_3(); }; // 这里使用宏来分发上面的回调,仿造MFC消息分发的方式 #define DECLARE_CBFUN_TABLE() / bool Function(unsigned int nMsg); #define BEGIN_CBFUN_TABLE(theClass, baseClass) / bool theClass::Function(unsigned int nMsg) / { / bool bHandle = false; / switch(nMsg) / { #define ON_CBFUN(nMsg, subFunc) / case nMsg:bHandle = subFunc(); break; #define END_CBFUN_TABLE(theClass, baseClass) / default: bHandle = baseClass::Function(nMsg); / } / return bHandle; / } // 使用宏 class KCBDoWith : public KCBBase { public: DECLARE_CBFUN_TABLE() bool SubFunc_1(); bool SubFunc_2(); bool SubFunc_3(); };
// .CPP
#include "stdafx.h" #include "KCBBase.h" // ------------------------------------------------------------------------- bool KCBWork::Function(unsigned int nMsg) { bool bRet = false; switch(nMsg) { case 1: bRet = SubFunc_1(); break; case 2: bRet = SubFunc_2(); break; case 3: bRet = SubFunc_3(); break; default: bRet = KCBBase::Function(nMsg); break; } return bRet; } bool KCBWork::SubFunc_1() { return true; } bool KCBWork::SubFunc_2() { return true; } bool KCBWork::SubFunc_3() { return true; } BEGIN_CBFUN_TABLE(KCBDoWith, KCBBase) ON_CBFUN(1, SubFunc_1) ON_CBFUN(2, SubFunc_2) ON_CBFUN(3, SubFunc_3) END_CBFUN_TABLE(KCBDoWith, KCBBase) bool KCBDoWith::SubFunc_1() { return true; } bool KCBDoWith::SubFunc_2() { return true; } bool KCBDoWith::SubFunc_3() { return true; }
// 使用
KCBDoWith cbDoWith;
KCBDoWith::CBFunc(&cbDoWith, 2);
[END]
相关文章推荐
- 使用Retrofit和Rxjava对联网进行简单封装
- Android Studio下使用JAVA+Appium进行自动化测试及简单封装
- 1个比较简单的使用java反射机制获取前台数据进行数据封装的例子
- 【Android】Retrofit的使用(3)-对Retrofit进行简单的封装
- js简单封装能向回调函数传入参数的事件处理函数
- poi导出excel,支持2007和2003,支持javabean,利用反射对poi进行简单封装,支持任意实体和乱序的excel表格
- 如何简单的下载一些小文件并保存在一个路径中(有些方法进行了封装)
- 对Fetch进行简单的二次封装
- Android安卓使用iosocket进行Socket通信简单封装优雅写代码
- 对数据库DML操作进行封装成简单的工具
- 对libpq进行简单的c++封装
- 使用C++进行WMI查询的简单封装
- js中用数组对一些验证进行简单的封装
- 第十七天dbutils的使用------Commons DbUtils(Apache)第三方的:只是对JDBC编码进行了简单的封装
- 使用闭包对setTimeout进行简单封装避免出错
- 利用Android回调机制对Dialog进行简单封装
- 对获取简单网页数据方法进行封装
- JSON相关的,数据彼此间的转化进行了简单地封装,源码如下,支持arc与非arc
- 对Pthread线程进行简单的类封装