Decorator Design Pattern

The Decorator design pattern attach additional responsibilities to an object dynamically.It is wrap up at another object.It will extend functionality of object without affecting any other object.Decorators provide a alternative to subclassing for extending functionality.

Also known as:

Wrapper

When to use it:

Use Decoraotor
  • to add responsibilities to individual objects dynamically without affecting other objects.
  • for responsibilities that can be withdrawn,
  • When extension by subclassing is impractical.Sometimes a large number of independent extensions are possible and would produce an explosion of subclasses to support every combination.Or class definition may be hidden or otherwise unavailable for subclassing.

UML diagram for decorator design pattern:

Elements:

  • Component
    • defines interface for objects that can have additional responsibilities added to them.
  • ConcreteComponent
    • defines an object on which additional responsibilities  can be added
  • Decorator
    • maintains a reference to component object and defines an interface that conforms to component’s interface.In simple words,It has a component object to be decorated.
  • ConcreteDecorator
    • add responsibilities to the component object.

Example:

In this example,we will decorate a simple room with color and curtains.
    • Room(Component)
      • It is an interface which creates a blue print for the class which will have decorators
    • SimpleRoom(ConcreteComponent)
      • Object of SimpleRoom class will be decorated.Additional responsibilities will be attached to it dynamically.
    • RoomDecorator(Decorator)
      • It contains reference to Room class which will be decorated.
    •  ColorDecorator(ConcreteDecorator)
      • ColorDecorator will add additional responsibility i.e.add color to room.
    • CurtainDecorator(ConcreteDecorator)
      • CurtainDecorator will add  additional responsibility i.e. add curtains to room.

Logically,you can think of decorator pattern as shown in above diagram.You will first created SimpleRoom object then decorate it with ColorDecorator object and then decorate resultant object with CuratainDecorator.

Java code for above classes:

The following interface is an interface depicting an room.
Room.java(Component):

Following class is a concrete implementation of this interface. This is the base class on which the decorators will be added.
SimpleRoom.java(ConcreteComponent) :

Following class is the decorator class. It is the core of the decorator design pattern. It contains an attribute for the type of interface. Instance is assigned dynamically at the creation of decorator using its constructor. Once assigned that instance method will be invoked.
RoomDecorator.java(Decorator):

Following class is our concrete decorator class.It extends abstract decorator.When this decorator is created,base instance is passed to constructor which calls super class constructor.In showRoom() method, we call base class method followed by its own method addColors.This addColors() adds functionality to base instance i.e. decorating  room with colors.
ColorDecorator.java(ConcreteDecorator):

Following class is also concreteDecorator class similar to above class.here addCurtains() add functionality to room(base instance) i.e. decorating room with curtains.
CurtainDecorator.java(ConcreteDecorator):

DecoratorDesignPatternMain.java:

I have created a simple Room and decorated that with color and curtains.
Output:

Advantages of decorator design pattern:

  • It is flexible than inheritance because inheritance adds responsibility at compile time but decorator pattern adds at run time.
  • We can have any number of decorators and also in any order.
  • It extends functionality of object without affecting any other object.

Disadvantage of decorator design pattern:

Main disadvantage of decorator design pattern is code maintainability because this pattern creates lots of similar decorator which are sometimes hard to maintain and distinguish.

Decorator Design Pattern in java API:

java.io.BufferedReader;
java.io.BufferedWriter;
java.io.FileReader;
java.io.Reader;
The above classes of java API are designed using decorator design pattern.

Source code:

Was this post helpful?

Related Posts

  • 25 June

    Convert Roman Number to Integer in Python

    Table of ContentsHow to Convert Roman Number to Integer in PythonHow to convert roman number to integer in python?Using the if...else statement to convert roman number to integer in Python.Using classes and a dictionary to convert roman number to integer in Python.Using the roman module to convert roman number to integer in Python.ConclusionWas this post […]

  • 11 June

    Remove Single Quotes from String in Python

    Table of ContentsRemove single quotes from string in Python.How to remove single quotes from string in Python?Using the replace() function to remove single quotes from string in Python.Using a for loop to remove single quotes from string in Python.Using the join() function to remove single quotes from string in Python.Using the re module functions to […]

  • 11 June

    Escape Backslash Character in Python

    Table of ContentsEscape backslash character in python.How to use escape backslash character in python?Using the escape backslash character in python to represent whitespace characters.Using the escape backslash character in python to turn special characters into ordinary characters.Using the escape backslash character in f-strings in Python.Using the escape backslash character in raw strings in Python.Was this […]

  • 11 June

    Remove Parentheses From String in Java

    Table of ContentsJava StringsRemove Parentheses From a String Using the replaceAll() MethodRemove Parentheses From a String by TraversingConclusionWas this post helpful? Java uses the Strings data structure to store the text data. This article discusses methods to remove parentheses from a String in Java. Java Strings Java Strings is a class that stores the text […]

  • 11 June

    Break out of function in Python

    Table of ContentsBreak out of function in PythonHow to break out of function in Python?Using the return statement to break out of function in PythonUsing the try and except block to break out of function in PythonUsing the sys.exit() function to break out of function in PythonConclusionWas this post helpful? In this post, we will […]

  • 11 June

    Check if Object Is Iterable in Python

    Table of ContentsWhat are iterables in Python?How to check if object is iterable in Python?Using the iter() function to check if object is iterable in PythonUsing the for loop to check if object is iterable in PythonUsing the isinstance() function to check if object is iterable in PythonConclusionWas this post helpful? In this post, we […]

Leave a Reply

Your email address will not be published.

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.