两个子级具有相同的 F() 实现,另外两个子级具有不同的 F 实现,所有四个子级都派生自同一类

two children has same implementation of F() , other two children has different implementation of F, all four derive from same class

本文关键字:实现 两个 派生 一类 四个      更新时间:2023-10-16

我有以下类层次结构。

class Base
{
 virtual void F();
}
class Derived1 : public Base
{
  void F() {
        cout<< " one implementation"<<endl;
  }
}
class Derived2 : public Base
{
  void F() {
        cout<< " one implementation"<<endl;
  }
}
class Derived3 : public Base
{
  void F() {
        cout<< " other implementation"<<endl;
  }
}
class Derived4 : public Base
{
  void F() {
        cout<< " other implementation"<<endl;
  }
}

像下面这样在层次结构中引入更多类似乎可以解决问题

class Base
    {
     virtual void F();
    }
class Base1 : public Base {
    void F() {
            cout<< " one implementation"<<endl;
      }
}
class Base2 : public Base {
    void F() {
            cout<< " other implementation"<<endl;
      }
}
    class Derived1 : public Base1
    {
    }
    class Derived2 : public Base1
    {
    }
    class Derived3 : public Base2
    {
    }
    class Derived4 : public Base2
    {
    }

我想知道是否可以更好地解决上述几个兄弟姐妹比其他兄弟姐妹具有相同实现的用例?我在这里缺少任何明显的设计模式吗?

如果 F 是我想要的唯一功能可能是我可以通过组合来解决它(见下文(。我不知道这样做是否是一个好主意。

组成

class Base
    {
     virtual void F();
    }
class Base1 : public Base {
    void F() {
            cout<< " one implementation"<<endl;
      }
}
class Base2 : public Base {
    void F() {
            cout<< " other implementation"<<endl;
      }
}
    class Derived1 
    {
      Base * Fer;
      Derived1()
      {
        Fer = new Base1();
      }
    }
    class Derived2
    {
      Base * Fer;
      Derived1()
      {
        Fer = new Base1();
      }
    }
    class Derived3 
    {
      Base * Fer;
      Derived1()
      {
        Fer = new Base2();
      }
    }
    class Derived4
    {
      Base * Fer;
      Derived1()
      {
        Fer = new Base2();
      }
    }

我会使用组合,但这样:

#include <iostream>
// define an interface
class Base
{
 virtual void F() = 0;
};
// define an implementation framework which pulls in templated
// components to do the work
template<class HandleF>
struct Impl : Base
{
    virtual void F() override {
        f_handler(this);
    }
    HandleF f_handler;
};
struct OneImplementationOfF
{
    template<class Self>
    void operator()(Self* self) const
    {
        std::cout<< " one implementation"<< std::endl;
    }
};
struct OtherImplementationOfF
{
    template<class Self>
    void operator()(Self* self) const
    {
        std::cout<< " other implementation"<< std::endl;
    }
};
// now build our classes    
class Derived1 : public Impl<OneImplementationOfF>
{
};
class Derived2 : public Impl<OneImplementationOfF>
{
};
class Derived3 : public Impl<OtherImplementationOfF>
{
};
class Derived4 : public Impl<OtherImplementationOfF>
{
};