Design Pattern
  • Introduction
  • What is singleton?
  • factory method design pattern
  • loose coupling VS tight coupling
  • Proxy pattern
  • abstracFactory
  • OOA & OOD
  • Decorator Design Pattern
  • Iterator Design Pattern
  • The Observer Pattern
  • Spring Singleton VS Java Singleton
Powered by GitBook
On this page
  • 1. Intent
  • 2. Problem
  • 3.Example

Was this helpful?

Decorator Design Pattern

PreviousOOA & OODNextIterator Design Pattern

Last updated 5 years ago

Was this helpful?

structural pattern

1. Intent

  • Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.

  • Client-specified embellishment of a core object by recursively wrapping it.

  • Wrapping a gift, putting it in a box, and wrapping the box.

2. Problem

You want to add behavior or state to individual objects at run-time. Inheritance is not feasible because it is static and applies to an entire class.

3.Example

In the above example the Pizza class acts as the Component and BasicPizza is the concrete component which needs to be decorated. The PizzaDecorator acts as a Decorator abstract class which contains a reference to the Pizza class. The ChickenTikkaPizza is the ConcreteDecorator which builds additional functionality to the Pizza class.

Let’s summarize the steps to implement the decorator design pattern:

  1. Create an interface to the BasicPizza(Concrete Component) that we want to decorate.

  2. Create an abstract class PizzaDecorator that contains reference field of Pizza(decorated) interface.

  3. Note: The decorator(PizzaDecorator) must extend same decorated(Pizza) interface.

  4. We will need to now pass the Pizza object that you want to decorate in the constructor of decorator.

  5. Let us create Concrete Decorator(ChickenTikkaPizza) which should provide additional functionalities of additional topping.

  6. The Concrete Decorator(ChickenTikkaPizza) should extend the PizzaDecorator abstract class.

  7. Redirect methods of decorator (bakePizza()) to decorated class’s core implementation.

  8. Override methods(bakePizza()) where you need to change behavior e.g. addition of the Chicken Tikka topping.

  9. Let the client class create the Component type (Pizza) object by creating a Concrete Decorator(ChickenTikkaPizza) with help from Concrete Component(BasicPizza).

  10. To remember in short : New Component = Concrete Component + Concrete Decorator

Pizza pizza = new ChickenTikkaPizza(new BasicPizza());