lundi 22 mai 2017

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

I have the following class hierarchy.

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

Introducing more classes in the hierarchy like following seems to solve the issue

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
    {

    }

I was wondering if the above use case of few siblings having same implementation than other siblings can be tackled better? Is there any obvious design pattern which i am missing here?

If F is the only functionality i want may be I can solve it just by composition( see below). I do not know whether it is a good idea to do that.

composition

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

Aucun commentaire:

Enregistrer un commentaire