I have been trying to figure out the best approach to this situation.
I have X number of class objects (these I DO NOT have the source code to, but they can all be subclassed)
to each of these I want to add 10 computed property values. The code for these are all the same… In that I mean while each of the 10 are different, each subclass requires the same code requirement
what I would like to do is come up with a way that I can encapsulate the new property code into a single “package”, so I don’t need to duplicate it for each subclassed object. It would be a simple copy/paste operation, but there has to be a cleaner way,
So I have Master class A, B and C
and create subclass A1, B1 and C1 where these have the 10 new properties.
I had thought of putting them all in Class D , and making D a property of A1, B1 and C1, but then calling the property would be A1.D.xyz where I really want it to be A1.xyz
How is that drastically different from my “use class D” suggestion… perhaps a small example project might help me visualize what you guys are suggesting
Personally I tend to favour the decorator pattern or some kind of composition approach in these situations. The constructor takes an instance of the master and holds a reference to it internally or possibly creates an instance of the master in the default constructor. Properties of the master are exposed via computed properties etc.
My thinking is that since I dont have access to the underlying library, I may be forced to swap it out later and a composition better insulates my application from a third party library.
I agree, it sounds like composition is what you want here.
Put the common code in its own class and have the subclasses forward calls to it.
Andrew’s technique uses an interface to relate the subclasses and then uses an extension method for the interface that calls the common code on D. So there is no A1.D.xyz. It would still be A1.xyz (which behind the scenes calls D).
Or you could skip the subclasses and interface entirely and create extension methods for the primary classes (A, B, C) that call the code on the common class D.