Decorator Pattern in Java

As the name suggests, it is all about decorating a solid entity.

Why Decorator ?

Decorating the nucleus of an atom😅

In a game, we created a class Atom. Different atoms have different degree of motion. Say for e.g. :-

Atom 1, has only 1 degree of motion — along x-axis
Atom 2, has 2 degree of motion — along x & y axis
Atom 3, has again 2 degree of motion — along y & z axis

Creating a separate class to handle this would be a tedious task. For e.g. :- MovableX, MovableXZ, MovableYZ … etc.

One alternative is to follow Decorator Pattern. ( Because less code duplication).

Create MovableX, MovableY, MovableZ and then use the combinations to dynamically add additional responsibility to individual atom.

E.g. :-

For MovableXY class, we could do create this

IAtom atom_x_y = new MovableX( new MovableY( new Atom() ) )

Project Structure:

Implementation in Java:

Take the example of a Window View(solid entity). Suppose we have to decorate Window with a new property Scrolling (additional responsibility).

Number of possible combinations(here combination is fine, rather than permutation)→ Horizontal, Vertical, Horizontal_&_Vertical.

Lets see how decorator could be used in this case.

  1. Create an Interface (code to interface not to implementation)

IWindow.java

2. Create a solid entity (Implementing the Interface)

BasicWindow.java

3. Create an Abstract Scrollable Decorator which accommodates the solid entity.

ScrollDecorator.java

4. Create Decorator Classes from Scroll-Decorator

NOTE:

  • window object is present in the Abstract class.
  • Scroll logic can be included inside the render().

VerticalScrollDecorator.java

HorizontalScrollDecorator.java

5. Driver Program

DecoratorDriver.java

  • IWindow is used rather than any Concrete class.
  • Note the order, of calling constructors.

Found it Interesting?

Reference:

Disclaimer:
I myself, has just started learning, design patterns. If you find any issues please feel free to post them in the comments section below. Thank you for reading so far 😄

Writes on Big Data, AWS & Backend technologies.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store