05 Decorator
05 Decorator
1
Decorator Pattern
A structural design pattern that lets you attach new behaviors to
objects by placing these objects inside special wrapper objects that
contain the behaviors.
Decorator Pattern
Welcome to our coffee
9
Constructing a drink order with Decorators
Constructing a drink order with Decorators
Computing the cost
13
Decorator Pattern
14
Decorating our beverages
Code of the Decorator
16
Coding beverages
17
Coding condiments (tastes)
18
Running the code
19
Another Example
21
Example
22
Example
23
Example
24
Decorator Pattern
Pros
Extending an object’s behavior without making a new subclass.
• You can add or remove responsibilities from an object at runtime.
• You can combine several behaviors by wrapping an object into
multiple decorators.
• Single Responsibility Principle. You can divide a monolithic class that
implements many possible variants of behavior into several smaller
classes.
Cons
• Hard to remove a specific wrapper from the wrappers stack.
• Hard to implement a decorator in such a way that its behavior
doesn’t depend on the order in the decorators stack.
Class diagram for Decorator Pattern
(unity example)
When to use the Decorator pattern
27
Attachments that the player could buy
BikeWeapon class
BikeWeapon class
BikeWeapon class
31
Weapon class
32
Testing the weapon system
Screenshot of the code example in action inside Unity
35
BikeWeapon component properties
36
37