Decorator Pattern in Java

Decorator Pattern is a Structural Pattern in which, functionality can be added to an existing object without changing its structure.


Decorator Pattern defines one or many Classes that wrap original Class. Everytime we decorate original Class with a Decorator Class, a functionality is added.
There is an abstract Decorator Class which implements Component interface to get its original operation() function, then each concrete Decorator override operation() method to add its own functionality decorate() using instance of original Class Component.
So, when Client wants to add more functionality, it just calls appropriate constructor method corresponding to specific Decorator.

1. Project Overview

At first, a person could buy a new House. We give him an option that he can pay more money to add a Garden around his house, and then, if he think he should have a Pool, we can create it for him.

So we need 2 Concrete Decorators: Garden and Pool extending abstract Class HouseDecorator.

2. Step by Step

2.1- Create IHouse interface and its implementation – SimpleHouse:

2.2- Create HouseDecorator abstract class:

2.3- Create 2 Concrete Decorators: Garden class and Pool class extending HouseDecorator:

2.4- Create Client Test Class:

2.5- Run the code, the console window shows:



By grokonez | March 18, 2017.

Related Posts

Got Something To Say:

Your email address will not be published. Required fields are marked *