Decorator Pattern

Tram Ho

Define

The decorator pattern modifies the behavior of a core object without changing its existing class definition.

The decorator pattern has two main components: a core object that will modify its behavior and a decorator object that brings change behavior in the core object.

These two components work together for two main goals:

  1. Behavior Modification
  2. Achieved Dynamically

Behavior Modification

The purpose of a pattern is to change the behavior of a core object without modifying its existing class implementation. This is achieved by wrapping the core object with decorators, which increases the default behavior of the core object.

The decorator enhances the behavior that already exists in the core object. They share the same interface with the core object, but provide a different implementation. Therefore, customers cannot distinguish whether they are working with a decorator or core object: they call the exact same functions / attributes on both. This shared interface allows home decorators to act as intermediaries, block calls to the core audience and provide custom behavior to customers.

Dynamic Modifications

Decorators do not simply modify behavior, they do so flexibly. In other words, they change the way objects behave at runtime instead of compile time.
Compiling modifying the time behavior is very simple: one just needs to change the definition of the object class, or subclass directly, and override its default settings. However, these options may be undesirable for the following reasons:

  1. The core object class can be declared at last, which prevents subclasses.
  2. This class can be defined in a third-party frame and any changes made to it will be lost in the next frame update.
  3. It is possible that many desired modifications exist and some behaviors can be interconnected to create complex combinations. Creating a subclass for every combination would probably result in a class explosion.
  4. Changes to existing classes can cause unintended side effects, from functional disruptions to crashes. This is especially true when inheriting a fragile legacy code base and not being fully understood.

Implement

Feel free to make models using race car illustrations.


We created a Transporting protocol, which requires suitable vehicle objects to provide us with their speed and traction indicators.

Using the RaceCar Class

Adding a Decorator
Share the news now

Source : Viblo