Which is your favourite Gun in PUBG?
Mine is this one in the picture below. Who will name this? SCAR-L! That’s right. It needs 5.56 mm bullet and is pretty handy. More about SCAR-L here.
But! let’s ask our friends in Pochinki? Has someone got 4x zoom?
Why? Because you know that the assault rifle works best with 4x zoom and while we are on it, we would also need compensator and suppressor. It will reduce recoil and reduce firing sound as well as echo. Eh! Pochinki can be heartbreaking, no wants to die soon.
Good for us! But Bad for PUBG developers!
Manager announced in the meeting that we will need to implement this feature where we will allow players to buy their favourite gun and their accessories. Players can buy the gun or some of the accessory or all of the accessory and they would be charged accordingly.
And one of the developers came up with the class diagram as shown below:
Meeting room was filled with questions:
"What if they want to add handle grip? Will we make six more classes?"
"And what about other guns? AKM would need 10 more classes? How many classes will we need? Such pain!"
"Can't we use Decorator Pattern here?, Looks like the perfect case for the decorator pattern here"
Well, the guy went back to his study table to learn decorator pattern and let’s see what he studied!
Woah! One chapter! And change in perspective of our developer.
"What If I just start with a gun, say SCAR-L and add the accessories as the player buy it?"
Let’s take it step by step. Suppose someone wants to buy SCAR-L with all three accessories mentioned above.
- Take an object of SCAR-L
- Decorate (or add) the SCAR-L with 4x zoom object
- Decorate the SCAR-L with suppressor object
- Decorate the SCAR-L with compressor object
- Call the cost method and let each object delegate to add on the cost using cost method of accessories.
Meeting called to discuss new class diagram using decorator pattern
Looks Good. Can we implement this?
Usual story, project wants to ship this feature asap. How would the implementation look like?
This class would be extended by all the guns. We will see that in a while. Let’s make an abstract class for gun accessory.
We are all set with example of AKM and Scar-L. Can we have some accessories please?
Time for a main Method
Now that we have seen an example of decorator pattern. Let’s define it briefly.
Decorator pattern attaches additional responsibilities to an object. Decorator pattern involves a set of decorator classes(like 4xZoom, Suppressor, Compensator) that are used to wrap concrete components(like AKM, Scarl). Decorator classes have the same type as components they decorate(Gun in our case).
- Decorators can result in many small objects
- Any number of decorators can be wrapped over the concrete component
- Decorators allow us to extend the behaviour without need to modify the existing code. For example, a plane gun can be extended to one with zoom
- Decorators are invisible to client
Liked it? Subscribe to get latest post