Posted onInDesign patternViews: Symbols count in article: 4.8kReading time ≈4 mins.
the decorator pattern is a design pattern that allows behavior to be added to an individual object, dynamically, without affecting the behavior of other objects from the same class.
In plain words
Decorator pattern lets you dynamically change the behavior of an object at run time by wrapping them in an object of a decorator class.
Wikipedia says
In object-oriented programming, the decorator pattern is a design pattern that allows behavior to be added to an individual object, either statically or dynamically, without affecting the behavior of other objects from the same class. The decorator pattern is often useful for adhering to the Single Responsibility Principle, as it allows functionality to be divided between classes with unique areas of concern.
Example
This example shows how you can adjust the behavior of an object without changing its code.
Initially, the business logic class could only read and write data in plain text. Then we created several small wrapper classes that add new behavior after executing standard operations in a wrapped object.
The first wrapper encrypts and decrypts data, and the second one compresses and extracts data.
- Input ---------------- Name,Salary John Smith,100000 Steven Jobs,912000 - Encoded -------------- Zkt7e1Q5eU8yUm1Qe0ZsdHJ2VXp6dDBKVnhrUHtUe0sxRUYxQkJIdjVLTVZ0dVI5 - Decoded -------------- Name,Salary John Smith,100000 Steven Jobs,912000
Difference between Adapter and Decorator patterns
Decorator, attach additional responsibilities to an object dynamically (i.e. at run-time, add new behavior without changing source code). For example adding sugar in a coffee.
Adapter, adapts interface of an existing class to another interface. For example eletrical adapter to conect three-legged plug with a two-pronged outlet.