DECORATOR DESIGN PATTERN

Let’s imagine we want to create a game, and for our superhero, we want to add a new gadget to every level of the game and gadget should be selected by the player.

How we can do¬†that?ūü§Ē

One way to do that use traditional inheritance, We will create a base abstract gadget class and multiple subclasses for different gadget combination.

But wait I have n numbers of gadgets so in my case I have to create n! subclasses.

If n = 5 then for 5 powers the number of subclasses will be 5! = 120. For 5 gadget we have to create 120 subclasses.ūüėĘ

Is there any other simple way to do that?

Yes, We can use Decorator Design Pattern to solve this problem.

Decorator Design Pattern allows behavior to be added to an individual object, either statically or dynamically, without affecting the behavior of other objects from the same class

Decorator Design Pattern comes under structural pattern. This pattern creates a decorator class which wraps the original class and provides additional functionality keeping class methods signature intact.

ironman.png

We will create a Gadget interface and concrete classes implementing the Gadget interface. We will then create an abstract decorator class GadgateDecorator implementing the Gadget interface and having Gadget object as its instance variable.

FlightGadget and UnibeamChestProjectorGadget are concrete classes implementing GadgateDecorator.

Suit class will implement Gadget interface and it will be our base gadget or first gadget.

Gadget.java

GadgetDecorator.java

FlightGadget.java

UnibeamChestProjectorGadget.java

Suit.java

IronMan.java

Main.java

Output:

Decorator Pattern provides greater flexibility than static inheritance. It enhances the extensibility of the object because changes are made by coding new classes.

Decorator Pattern can be used when we want to add responsibilities dynamically at runtime.