0

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.

Kevin. J
  • 35
  • 8

1 Answers1

0

what you need is the "Composite", not the "Decorator". Decorators are normally used to add cross-cutting concerns to objects, like logging, instrumentation, retry policies and so on.

In your case instead you need a generic GameObject class, holding a Components collection. A Component is something that adds behaviour to an entity, like AI, stats, physics and so on.

This way you can avoid creating tons of classes like "Player", "Enemy", "Boss", "MegaBoss" and so on. Just define the necessary components and add them on the GameObject and you're done.

David Guida
  • 950
  • 9
  • 19
  • AOP is normally used to add cross-cutting concerns. Decorators are something else. – jaco0646 Dec 18 '20 at 19:21
  • Yes, AOP can be used too, although it may make DI a bit more complex. Personally I prefer using Decorators for these things. What would you use them for? Please elaborate. – David Guida Dec 19 '20 at 20:57
  • In Java, the [quintessential example](https://stackoverflow.com/questions/3068912/what-is-the-most-used-pattern-in-java-io) is the various Readers and Writers in the IO package. – jaco0646 Dec 20 '20 at 15:43
  • well, I raise you with this: https://blog.ploeh.dk/2010/04/07/DependencyInjectionisLooseCoupling/ Mark Seemann is always a great source. – David Guida Dec 21 '20 at 03:30