vendredi 10 août 2018

Composite pattern with variations in classes

I have a situation where class A, B, and C, all are derived from X to make a composite pattern.

Now A, B, and C are very similar but they do have different internal attributes. My question is how do I access their attributes and modify them once they are added to composite without typecasting it?

In my real example, the part-whole relationship totally makes sense and all elements support the main operation which is why I need it. That said individual classes in the composite does have different attributes and requires special operations.

Is there a way to decouple these special properties and functions related to them away from composite class but attach to them?

To put this in perspective, let's say you have composite merchandise (base class of composite) which has a price. Now a store is merchandise, in it a department is merchandise, in which an actual item say a potis merchandise, it can have a pot-set with combination pots which is also merchandise and so on.

The problem is with this line once I have filled up the composite.

Merchandise * item = store->GetItem()->GetItem()->getMerchandise();

First, from my code structure, I know this should be a pot but as best practice, I shouldn't typecast this? But I want to change its properties which are unique to it so how do I achieve that?

Assume the store sells shirts as well and if I want to change its properties, it is very different from a pot.

What would be the best approach here? I think if we can somehow decouple the special properties of each composite into different classes, this way composite will stay leaner too but not sure how to achieve that.

I do assume, in real life, there is no perfect composite and the constituent classes will have some differences. How do we handle that?

Aucun commentaire:

Enregistrer un commentaire