Decorator Pattern

 
Looking at the ability system, I can add a Delay Decorator to make it more flexible. The Decorator will be an Ability and utilize Use in its own manner. Now it will utilize composition to have an ability that it delays rather than rewriting the FireBall code or deriving from FireBall. As a result, we can postpone the opportunity to use another Delay Decorator.

What I have in the end is the Ability Runner pointing to a Fire Ball instance of the Delay Decorator.


 
The Decorator Pattern is what is used here.
 
 

Defined Decorator Pattern


 
The decorator pattern is a design pattern used in object-oriented programming that enables the dynamic addition of behaviour to a single object without changing the behaviour of other objects belonging to the same class. Because it enables functionality to be partitioned amongst classes with distinct areas of concern, the decorator pattern is frequently helpful for upholding the single responsibility principle. Using a decorator can be more effective than sub classing since it allows for the enhancement of an object's functionality without establishing a brand-new object.

This means that an existing object can have additional functionality added to it without having its structure changed. Given that it works as a wrapper for pre-existing classes, this kind of pattern falls within the structural pattern category. It executes the interface and receives all requests. Additionally, it performs functions both before and after sending a request. The Adapter Pattern and Facade Pattern both provide different approaches for resolving issues as alternatives. Sometimes the Facade pattern is combined with the Decorator pattern.

Decorator as an abstract class
You may occasionally see it used in this way. Assume that the Concrete Decorator inherits from the decorator, an abstract class that derives from the interface.
 

 

Implementation

Delayed Ability
 

 
Making use of the IAbilty Interface, I construct the Delayed Decorator.
 

 
I add an IAbility so that the delayed decorator has it.

 
Of course, I need to ensure that the constructor sets the ability to what it should be.
 

 
I complete the IAbility Interface last.
 

 
I can now make advantage of my delayed decorator ability. Instead of setting the Ability in my Ability Runner class to be the Fireball ability, I assigned it to a new Delayed Decorator ability that also contains the Fireball ability.
 

 
I now utilize the Delaying ability when I employ the Fireball ability.
 

 
Cool Down Ability
The Decorator can of course also execute code after the ability.
 

 
My Rage Ability must now cool down in order to be activated.
 
m_currentAbility = new CoolDownDecorator(new RageAbility())


 
Thank you for reading the Decorator Pattern in Unity article.
 
Category: Unity | Added by: Viktor_Surzhko (2021-10-01)
Views: 1028 | Rating: 0.0/0
Total comments: 0
avatar