Reputation: 37
The exercise is about making a software to manage a Robot Factory.
In my program I can create single parts and then robots with them but I also can have robots with smaller robots inside. That's where the Composite comes in. In fact the Component class could be a Part and the Composite class the Robot that implements a list of Parts and inherits from the Part class (that's because a robot can also be made from a single part)
Everything points to this solution but the problem comes when they told us that there are 2 types of Parts; Terrestrial and Aquatic and a Robot cannot be made with different types of parts.
I don't know if this is actually a viable way because the diagram implies I can have a Robot made with both kind of parts even though I'm going to limit it within the code.
Here's an UML diagram
Upvotes: 0
Views: 1020
Reputation: 42229
Here is a CodeReview article I wrote on Multiple Inheritance and the Composition Pattern using generics.
This might give you some ideas of how to write the implementation. It appears that what you are talking about, in some respects, is polymorphism.
Firstly, yes you can use the composition pattern to achieve your goal, but do not forget the use of interfaces as well!
Upvotes: 1
Reputation: 261
Here we have 2 solutions for this problem:
They are basically the same, although you are sparing the use of the "xor" restriction on the right, and trading it for added complexity.
There is a subtle difference between this 2 solutions. On the left, you can't have a robot without at least 1 aquatic or terrestrial part (which wasn't mentioned initially). On the right, you can have a robot without parts (which wasn't mentioned either).
By changing multiplicities in both solutions, you can choose between a robot with no parts at all or a robot that needs at least 1 part which isn't a Robot. This isn't ideal, and the Composite pattern doesn't suffer from what I've just mentioned. I can't picture a better solution though.
Upvotes: 2