避免公共类中的代码重复
Avoiding duplication of code in common classes
本文关键字:代码 更新时间:2023-10-16
我有一个回调函数,称为
MyCallBack(int type)
我有3个类B、C和D,它们派生自具有公共方法名称的A目前我的代码是这样的
MyCallBack(int type){
if(type == 1 ){
B b;
b.perform();
}else if(type==2) {
C c;
c.perform();
}else if(type ==3){
D d;
d.perform();
}
有没有一种方法可以像一样减少这个代码
MyCallBack(int type){
Common object(type);
object.perform();
}
基本上,您需要的是多态性。
所有的类B
、C
、D
都应该派生自抽象类,比如说SuperBase
,使用纯虚拟方法perform()
您的代码应该只使用指向SuperBase
的指针,该指针包含实际具体类对象的地址
一旦有了这个,根据所指向对象的实际类型,将调用相应类中的方法。
这种方法的优点是没有硬编码类型检查&以及使用开闭原理的松耦合设计的灵活性。
@Als使用多态性的想法是一个很好的想法(IMO),但它只有在从输入整数转换为实际类型后才真正有效。一种方法是索引到对象的指针数组中:
MyCallback(int type) {
static A *ptrs[] = { new B, new C, new D};
ptrs[type-1]->perform();
}
编辑:如果您没有意识到,为了正确工作,perform
需要是一个在A
中声明(可能是纯)virtual的虚拟函数,并在B
、C
和D
中定义。您需要确保函数的整个签名,而不仅仅是名称,在类之间是相同的。
接口怎么样?
class A
{
public:
virtual void perform() = 0;
};
class B : public A
{
public:
void perform() { ... }
};
// Same for C, and D
所以你的回调看起来像:
MyCallBack(A& performer)
{
performer.perform();
}
如果你不能更改回调的签名,那么抽象的工厂模式:怎么样
function A* AFactory(int type)
{
switch(type)
{
case 1: return new B(); // Assuming B, C, D all derive from A
case 2: return new C();
case 3: return new D();
default: return nullptr; // nullptr is a c++11 thing. Use NULL, if you're still on C++03
}
}
然后回调。。。
MyCallBack(int type)
{
std::unique_ptr<A> obj(AFactory(type)); // this will automatically release the memory once it falls out of scope
obj->perform();
}
您应该创建对象工厂,或者只创建静态(全局)方法,返回指向基类型的指针(或者引用),但由派生类型的对象组成。
CBase* CreateObjectBasedOnType(int type)
{
// check for type and return appriopriate derived object
}
MyCallBack(int type)
{
CreateObjectBasedOnType(type)->perform();
}
请注意,要调用的方法应该是虚拟的。
更好的方法可以使用模板
template<typename T>
MyCallBack()
{
T Obj;
Obj.perform();
}
相关文章:
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 代码在main()中运行,但在函数中出现错误
- 在VS代码中交叉编译Windows与Linux上的MinGW的SDL程序
- 编译包含字符串的代码时遇到问题
- 我在c++代码中生成了一个运行时#3异常
- 如何在linux终端中同时编译和运行c++代码
- 为cl.exe(Visual Studio代码)指定命令行C++版本
- 在Linux for Windows上编译C++代码时出错
- 我的字符计数代码计算错误.为什么
- 孤立代码块在结构中引发异常
- 在编译C++代码(具有dlib和opencv)到WASM时面临问题
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- 此代码是否违反一个定义规则
- 为什么我的代码在输出中增加了93天
- 我的简单if-else语句是如何无法访问的代码
- 使用动态分配的数组会导致代码分析发出虚假的C6386缓冲区溢出警告
- 为什么在这个代码结束循环中没有得到结束
- 在c代码之间共享数据的最佳方式
- 这个指针和内存代码打印是什么?我不知道是打印垃圾还是如何打印我需要的值