Decorator Pattern in Java

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

I. OVERVIEW

Decorator Pattern defines one or many Classes that wrap original Class. Everytime we decorate original Class with a Decorator Class, a functionality is added.
decorator-pattern-overview
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.
decorator-pattern-structure
So, when Client wants to add more functionality, it just calls appropriate constructor method corresponding to specific Decorator.

II. PRACTICE
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.
decorator-pattern-demo

2. Step by Step

2.1- Create IHouse interface and its implementation – SimpleHouse:

IHouse.java

SimpleHouse.java

2.2- Create HouseDecorator abstract class:

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

Pool.java

2.4- Create Client Test Class:

2.5- Run the code, the console window shows:

III. SOURCE CODE

DecoratorPattern


Related Posts


Got Something To Say:

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

*