# Decorator Design Pattern

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

![](/files/-LgDobiq3Eq4fGaAN_k_)

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());


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://lin-4.gitbook.io/design-pattern/decorator-design-pattern.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
