This pattern allows you to add new behavior to existing objects dynamically, by wrapping them in an object of a decorator class. This can be useful when you want to extend the functionality of an object without subclassing it, and when you want to be able to add and remove responsibilities to an object at runtime.
Here is an example of the decorator pattern in JavaScript:
}
}
}
}
}
}
}
}
}
}
decoratorB.
// Output:
// ConcreteComponent operation.
// ConcreteDecoratorA operation.
// ConcreteDecoratorB operation.
In this example, the Component class is an abstract class that defines the interface for an object that can be decorated, and the ConcreteComponent class is a concrete implementation of the Component class that represents an object that can be decorated. The Decorator class is an abstract class that extends the Component class and has a field for storing a Component object. The ConcreteDecoratorA and ConcreteDecoratorB classes are concrete implementations of the Decorator class that add additional behavior to the decorated object.
To use the decorator pattern, we first create an instance of the ConcreteComponent class, which represents the object that we want to decorate. Then, we create instances of the ConcreteDecoratorA and ConcreteDecoratorB classes, passing the ConcreteComponent object as an argument to the constructor.
This creates a decorator object that wraps the ConcreteComponent object and adds additional behavior to it. When we call the operation() method on the outermost decorator object, it calls the operation() method on each of the decorator objects in turn, as well as the operation() method on the wrapped ConcreteComponent object, adding the additional behavior to the original object.