dimanche 2 août 2020

How to add functionality from combination of different derived class?

I have multiple handlers derived from base Handler class which can do single data updates individually.

For eg.

class Handler {
private: 
  Data_t dbdata_; 
public:
  virtual void updateFlags() = 0; 
}

class AHandler: public Handler {
.....
public:
  void updateFlags() { dbdata_.flagA = 1; }
}

class BHandler: public Handler {
.....
public:
  void updateFlags() { dbdata_.flagB = 1; }
}

class CHandler: public Handler {
.....
public:
  void updateFlags() { dbdata_.flagC = 1; }
}

Individual handlers are called based on input flags in request. If request contains multiple flags, then in this case I want to try to avoid creating additional 6 handlers individually like following.

class ACHandler: public Handler {
.....
public:
  void updateFlags() { dbdata_.flagA = 1; dbdata_.flagC = 1; }
}

class ABCHandler: public Handler {
.....
public:
  void updateFlags() { dbdata_.flagA = 1; dbdata_.flagB = 1; dbdata_.flagC = 1 }
}

Main function code will be something similar to this.

void process(Request_t *request)
{
  Handler *handler;
  if (request->flagA)
    handler = new AHandler();
  else if (request->flagB)
    handler = new BHandler();
  ....
  ...
  handler->updateFlags();
}

Is there a better way to approach this problem, by re-writing how the handlers are connected to each other ?

Thanks in advance.

Aucun commentaire:

Enregistrer un commentaire