Java : Decorator Design pattern

Decorator Design pattern:

Decorator is a structural design pattern that lets you attach new behaviors to objects by placing these objects inside special wrapper objects that contain the behaviors.

Example:

Assume: A notifier class/object can send only email messages. But the application at a later time may want to use text/SMS, FB, or similar messages. With decorator pattern: decorate the Notifier class with other behaviours such as send SMS, send fb message, send twitter message (i.e. may create additional classes/objects (create link to original notifier class with interfaces/inheritance and aggregations/compositions) ). Then the client can use the original notifier class/object but dynamically point to the other classes/objects and use the corresponding sendMessage() method/behaviour for SMS, Text, FB, Twitter or similar messaging/notification.

Note: Inheritance/subclasses can be a choice but they have limitations. Aggregations/Compositions/interfaces will be used for the purpose of Decorator pattern.

Note: “When does a simple wrapper become the real decorator? As I mentioned, the wrapper implements the same interface as the wrapped object. That’s why from the client’s perspective these objects are identical.

Ref: https://refactoring.guru/design-patterns/decorator

https://en.wikipedia.org/wiki/Decorator_pattern

Leave a Reply