I have five classes A, B, C, D, E that are unrelated (really more like 20).
I have to create five classes A_X, B_X, C_X, D_X, E_X that have almost identical APIs to A, B, C, D, and E, except that the X versions actually contain lists of A, B, C, D, E.
For instance, double A::value() const just returns the value of A, but double A_X::value() const returns the sum of all the A::value()'s that are in A_X's internal vector<A*>.
I can code this out in obvious ways, but it will result in a ton of boiler-plate code.
Is there a Design Pattern that fits what I am trying to do?
I've looked into things like layered mixins, but they seem to overly complicate code without great benefits, at least in my case...
Thanks in advance.
(BTW, A and A_X do not need to share a common super-class, but I'm open to solutions in which they do or don't - OOP/template solutions are all ok.)
There are two requirements:
1. A_X contains vector<A*>, etc...
2. When I add a new method foo(), I hope the design pattern makes it obvious that I need to add it to both A and A_X.
thx, ne555, for your suggestion, but A_X definitely needs to be in its own class of some kind because there are many attributes of X that will need aggregation
but your idea is good - perhaps I should use a similar API to STL for ease-of-use
I've thought about this some more and figured that I shouldn't care too much about the boiler-plate code
More important is that I code up the idea of Aggregation and Distribution once no matter how many classes I have - this implies some kind of template class or template function, I think...
Maybe something like
1 2 3 4 5
A_X a_x;
vector< A > v_a;
// put some A into v_a ...
a_x = Aggregate( v_a );
v_a = Distribute( a );
but I may have to add an AggregationProtocol and a DistributionProtocol as a second argument - AggregationProtocol should be some kind of key generator (eg AggregateOnHairColor), while the DistributionProtocol should be some kind of weight generator (eg EvenWeighted or PercentWeight)
The system so be flexible enough that I wouldn't have to recode any of this for A through E vs A_X through E_X...
If you want A and A_X to share multiple common interface methods, i think the obvious solutions are :
- Making an abstract class parent of those two that has all those interface methods,
- Making a template class that has the interfaces methods you need, and adding to A and A_X the methods the template class will need to implement it's methods
- Making A a child class of A_X with the particularity that it's container size is limited to 1
The below should be appealing enough: I don't know how different A, B, C, D and E are, but the template could be use for all of them as long as enough properties are shared.