This post is part of the Programming Design Concepts course, if you wish to learn about other design patterns then I suggest you check the main page: Programming Design Concepts

Decorator Pattern

The decorator pattern is also known as the Wrapper pattern and it’s primarily used when we want to add responsibilities to individual objects, not to an entire class. Say for instance we have an Enemy class in our game with loads of Enemy objects running about, if we wanted to add a special ability to one of these objects we would use the Decorator design pattern. This is opposed to having our Enemy class inherit from a Special abilities class as it would mean every Enemy would then gain this ability when in reality we only want one specific enemy gaining it.

UML Diagram

Decorator Design Pattern Tutorial

Pros and Cons:

Pros:

The best thing about the decorator pattern is the flexibility that it provides at runtime. We can customize instantiated objects dynamically and add or delete functionality for this object whenever we see fit. For game developers this can be hugely beneficial as we can now dynamically add more responsibilities to our instantiated objects / characters and provide a far more interesting gameplay experience. This Pattern also prevents the creation of feature-bloated classes high up in the hierarchy. It allows you to define far more simple classes and customize them by adding on any extra functionality incrementally with Decorator objects. It again forces us to program towards an interface which has been recognized as a best practice.

Cons:

The decorator pattern based system tends to be composed of lots of little objects that are very similar in nature. They differ only in the way they are interconnected, not in their class or in the value of their variables. As a result they can be hard to learn initially and even harder to debug. Implementation: In this example we shall be implementing a Character interface which will be implemented by our Player1 class. This player1 class will then be decorated by both a helmet and a shield class which are both extensions of the CharacterDecorator class.