Home > Net >  C Interface, What's the best way to not duplicate code
C Interface, What's the best way to not duplicate code

Time:12-16

I have this problem:

I have an Event Manager that call the event function do()

Event *p; 
//p takes it values from an Event Queue
p->do()

Some Events have two attributes Object a and b

class EventX : public Event {

   public : 
       EventX();
       void do(){actionX(a, b)}
   private : 
       Object a;
       Object b;
       bool bothSide;

};

class EventY : public Event {

   public : 
       EventY();
       void do(){actionY(a,b);}
   private : 
       Object a;
       Object b;
       bool bothSide;

};

do() is a function that carries out an action from a to b. I want to create an interface that can call do() from a to b and do() from b to a if bothSide attribute is true. Is that possible ? I have many Event with differents do() functions that perform different actions from a to b.

Thank you for reading

CodePudding user response:

You can have extra layer with another interface

struct EventAB : Event
{
    void do() final { if (bothSide) action(b, a); action(a, b); }
    virtual void action(Object&, Object&) = 0;

/*...*/

private:
    Object a;
    Object b;
    bool bothSide = false;
};

And then

class EventX : public EventAB {
public:
    void action(Object& lhs, Object& rhs) override { actionX(lhs, rhs); }
    // ...
};

class EventY : public EventAB {
public:
    void action(Object& lhs, Object& rhs) override { actionY(lhs, rhs); }
    // ...
};
  • Related