I have the same problem as this I have some problems about this project?, but due to the title was poorly written, the topic has been closed.
Basically, I have n classes, derived from a base class. Build a new class with its behaviors and attributes are based on matched combination (predefined) of those derived classes.
In his code he used a lot of if cases to find out the combination, which is cumbersome and the expandability is almost impossible. Can a design pattern replace those if cases?
E.g:
A+B+A = B+A+A = ... = A+B (combination 1)
A+A+A = no combination
Pseudocode:
class base
class A : public base
class B : public base
class C : public base
class combine : public base{
void combine(base&, base&, base&){
if(isA && isB && isC)
//implement combination1 here
else((isA && isB)) || (isB && isA))
//implement combination2 here
else(...)//and a lot more
}
};
Update #1:
Why combine
class is derived from base? As example in the link, combine
is still just a Robot
(base
), with superior stat.
Found out that Decorator is pretty suitable for this problem, however, still need if cases to determine which Decorator to use (at least it's now outside the class)
Pseudocode:
class decorator : public base{
protected:
base* m_base;
public:
m_base& setStat(base&);//set stat for m_base
}
class A_and_B : public decorator
class A_and_C : public decorator
//more combination
base* combine(base&, base&, base&){
combine megatron;
if((isA && isC)) || (isC && isA)){
A_and_C decor;
return decor.setStat(megatron);
}
else((isA && isB)) || (isB && isA))
A_and_B decor;
return decor.setStat(megatron);
}
else(...)//and a lot more
}