| |||||||||
computer programming, a decorator pattern is a design pattern that attaches additional logic to an existing object. It is used when something about an object needs to change. Objects can have attributes that change something about them.
Decorators provide a flexible alternative to subclassing for extending functionality.
A taco vending program that has a class 'Taco' representing a standard taco order which includes beef, cheese, and beans. But some customers also want sour cream. In the subclassing approach, you might make a 'TacoWithSourCream' subclass for 'Taco'. However, there are many other custom variants that could be desired, and the number of subclasses could grow unmanageably large.
Instead, one could design the 'Taco' class to include a list of ingredients. By default this list could include ['beef', 'cheese', and 'beans'], but during the order process, ingredients could be added or removed as needed, like 'decorations' placed onto the base.