Design Pattern: Decorator Pattern

Tram Ho

I. Introduction:

Decorator Pattern is a Design Pattern of the Structural group. It allows us to add new behaviors to an object ( wrapped object) by placing that object into another object ( wrapper object) containing the behavior to be added.

  • Component Interface : Defines properties and methods for wrappers and wrapped objects.
  • Concrete Component : is a basic wrapped object, it allows Decorators to wrap it inside to add new behaviors . Concrete Component will implement the Component Interface .
  • Base Decorator : is the parent class of Concrete Decortors , it also implements Component Interface . Inside the Decorator will contain the object of a wrapped object and will also have methods similar to that wrapped object.
  • Concrete Decorator : A class that extends Base Decorator , which defines new behaviors that need to be added to wrapped objects.

II. How it works:

Decorator Pattern works by creating many objects that are Concreate Decorators to surround each other. Whenever a new behavior needs to be added to an object, the Decorator Pattern will create a Concreate Decorator to handle the behavior, and this Concrete Decorator will be the new object (wrapper object) that wraps the old object (wrapped object).

III. When is the Decorator Pattern used?

Decorator Pattern is used when you want to add behavior to an object without changing the structure of the object.

IV. For example:

Component protocol

Concrete Component

Base Decorator

Concrete Decorator


V. References:

Share the news now

Source : Viblo