jeudi 17 décembre 2020

How to build stuff objects using the decorator pattern?

I have some questions regarding the decorator pattern. As I have understood it, the decorator pattern exists to add behaviour to an object, ie "decorating the object" so you can compose different objects without the need of implementing lots of lots of different classes with small changes, leading to a "class explosion".

Now the thing is, the decorator pattern generalised says the we should have a base class which our decorator class then extends, but also delegates from. So the decorator essentially both "is a" and "has a" base class (and with that it's methods).

And there comes the problem, because let us say I want to compose a "player" for a game, many different players actually and all with small changes. Then I might want to use the decorator pattern(?) and say "okay our base class is a normal human". I want to decorate this human with a gun and with body armor. Then my decorator class gun will implement the same methods that the human has, let us say "eat". But surely my gun won't eat, I only want it to be able to shoot. And I can fix that by just returning null or something but that would also break the Interface Segregation Principle.

So how would I then solve this without breaking the ISP while also not needing to create tons of classes with minimal changes, for example "human with gun", "human with gun and body armor", "human with staff and body armor", "human with staff", you get the idea.

Aucun commentaire:

Enregistrer un commentaire