Search code examples
c#design-patternscomposite

Composite Pattern in C#


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

enter image description here


Solution

  • Here we have 2 solutions for this problem:

    Robot UML

    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.