Decorator Pattern in Java

by | Sep 21, 2020 | Java

The Decorator Pattern, as the name suggests, has an ornamental function of adding features and attributes of existing objects. Functionalities of objects are added using wrapper classes either dynamically or statically. This patter finds use all the time in programs as developers are constantly in the process of increasing code efficiency and adding features.

Definition

The Decorator Pattern is defined as a structural design pattern in JAVA that adds functionality and attributes to existing objects by wrapping it with wrapper classes without changing the original class.

An object can be wrapped as many times as required. The design pattern applies the changes to an object at run time. Care needs to be taken that the original class and method signature is not changed or altered in any way when attempting to add features to an object.

Example and Code

The example below is that of a newly built hotel that requires interior decorations. We will only add a few wall paintings as part of this example to give a grandeur look to the hotel.

//Creating a Hotel interface

public interface Hotel {
String interiorDecor();
}

//This is an implementation class that will extend the hotel class.

public class HotelDecor implements Hotel {
@override
public void interiorDecor() {
System.out.println (“Hotel: Interior Decoration”);
}
}

//The class below will call the interior Décor method from the main interface. It will be an abstract //class that will store the same object and will implement the Hotel class.

public abstract class HotelInt implements Hotel {
private Hotel walls;

@override
public void interiorDecor()
}

//Now let us wrap the object with some paintings on the walls of the hotel.

public class Paintings extends HotelInt {
public wallPaint(Hotel walls) {
super(walls);
}
public void decorate () {
System.out.println(super.interiorDecor + “Paintings have been hung on the walls”);

 

When to use the Decorator Pattern?

As mentioned before, the decorator pattern is used to add functionalities to objects. Therefore, this pattern will find the best use in programs that are already well-defined but require modifications in the object level. All you need to do is wrap the objects to add the desired attributes.

Author

0 Comments

Submit a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Go Coding