避免公共类中的代码重复

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();
}

基本上,您需要的是多态性。

所有的类BCD都应该派生自抽象类,比如说SuperBase,使用纯虚拟方法perform()
您的代码应该只使用指向SuperBase的指针,该指针包含实际具体类对象的地址
一旦有了这个,根据所指向对象的实际类型,将调用相应类中的方法。

这种方法的优点是没有硬编码类型检查&以及使用开闭原理的松耦合设计的灵活性。

@Als使用多态性的想法是一个很好的想法(IMO),但它只有在从输入整数转换为实际类型后才真正有效。一种方法是索引到对象的指针数组中:

MyCallback(int type) { 
    static A *ptrs[] = { new B, new C, new D};
    ptrs[type-1]->perform();
}

编辑:如果您没有意识到,为了正确工作,perform需要是一个在A中声明(可能是纯)virtual的虚拟函数,并在BCD中定义。您需要确保函数的整个签名,而不仅仅是名称,在类之间是相同的。

接口怎么样?

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();
}