Click here to Skip to main content
Click here to Skip to main content
Go to top

Decorator Design Pattern Simplified

, 15 Dec 2013
Rate this:
Please Sign up or sign in to vote.
Explaining Decorator Design pattern and its implementation

Introduction

The easiest way to extend some feature of a Class is to use inheritance. But with inheritance it became very difficult to change the code or even some time extend the functionalities. One better solution to overcome some of the deficiencies of inheritance is to use decorator design pattern.  This article explains what decorator design pattern is and explain some of its implementation. The user will learn about the decorator pattern, some of its advantages and how it is implemented in some frameworks such as java and .net. This article will explain definition of the decorator design pattern and its class diagram and then briefly describe its implementation in java and .Net. 

What is Decorator Design Pattern 

The base of the decorator pattern is that we use composition in decorator pattern. What is composition? Lets understand with the help of a simple example: 

Class TestClass{  

Class1 objA = new Class1();
	Void myOwnMethod()
{
// do some work
	objA.SomeOneOhterMethod();
// do some my own work..
}
}  

 In this example code TestClass refer to Class1. This is called composition. Composition means holding the reference to another class. 

We use inheritance to extend some of the functionality of any class. In the similar way we can use composition to extend some of the functionality of any class. For example in the above example TestClass can extend the functionality of Class1 by simply calling the method of Calss1 and adding its own behavior before or after the method implementation of Class1 object. 

Let’s look at the implementation of how can we use inheritance to demonstrate the same feature as in the above code snippet: 

 Class Class1{
Void  SomeOneOhterMethod() {
	// Base class implemetnation
}}


Class TestCalss : Class1
{
Void myOwnMethod()
{
// some sub-class own work before
Base.SomeOneOtherMethod();
// some sub-call own work after..
}
}

As one we can see I can use both inheritance and composition to extend the behavior but it is recommended to use composition instead of inheritance for the extension of the behavior.  

Now after the concept of composition let's move to another concept which is called polymorphism or type matching. In simpler words when using inheritance one can use base class in place of its children class. But in composition example one can’t use Class1 in place of TestClass. Because both classes are of different types.

Type matching is very strong concept of object oriented programming and is used in many places for providing an abstraction layer. Type matching is only possible if we use inheritance.

Here is a question arrive that how can we use the benefit of type matching and composition in the same place? Decorator design pattern is an answer to that question. 

Now as discussed earlier decorator pattern can be used to gain advantages of inheritance and composition. In decorator pattern we used composition for extending behavior whereas uses inheritance for matching the type.

Lets see what is the textbook definition of the decorator pattern is and then one can compare it to the above example to get the grasp of the concept:  

“Decorator provide a flexible alternative to sub-classing for extending functionality” 

AND 

“The decorator pattern attaches additional responsibilities to an object at dynamically.”  

This second line of definition I will explain in the advantages of the decorator pattern.
  

Class Diagram and implementing guidelines 

 

This class diagram shows the implementation of decorator pattern for the above code snippets. A very simple example that how can we add benefit for both inheritance and composition in one place. In this diagram TestCalss is the decorator to Class1 and Class1 is the component. TestClass extends or inherit from the class1 as well as it contains a reference (composition) of class1. This Reference is used to add any additional behavior and inheritance is used for type matching. 

 Now let’s look at the text book class diagram:  

Here is a class diagram which is using abstract classes instead of concrete classes. Where as in my class diagram I have directly used the concrete classes. Both are correct but text book class diagram provide a more flexible way.

Instead of using the concrete component we are extending from the abstract Component class. Similarly decorator class is also abstract. Here concrete decorator adds the additional responsibilities to concrete component through composition.

Advantages   

Prevent Class explosion  

Suppose you have four classes which extend from the same super-class. Lets suppose a  new class is required which add to some functionality to superclass. In order to implement you need to implement this for the all the four classes. In this way you have four new classes for additional functionality for each implementing class. Similary all four classes need 16 classes to cater this changed. In total you have 20 Classes to implement and maintain.   

Take for instance you have a file type and two classes that extends them Chinese and French file system. Now after some time you that some files contain a specific word at the start other contain frame specific word at the end. You will need to extend from the same class and the class diagram will look like this: 

 

Let’s suppose there is another system for binary file is available. Now we have four more classes such as frameSyncChineseFilesBinarySystem and etc.

This causes four more classes to extend the same base class and will result in huge number of classes. By using decorator pattern we can eliminate these problems. For above example we can create 2 component ChineseFileSystem, French File system and 2 decorator around them one is for frame sync and one is for Binary system. This will reduce the number of classes. We can wrap this BinarySystem File with all component (e.g. Chinese File System) as well as wrap frame sync with all component. We can also wrap multiple times such as wrapping chinesefileSystem with FrameSync and then with Binary File System.

Hence by not using inheritance and using composition we prevented the syndrome of too many classes in a design.

New behavior can be added dynamically 

Since we use composition for adding behavior to the component classes we can add behavior (even remove) behavior at run-time. Since we have to create the reference to object at run-time therefore we can add or remove the behavior dynamically. On the other side in inheritance we have to describe the behavior at compile time.   

Inheritance for type matching so that one can mix and match

Inheritance is used for type matching because in this way the wrapping class(decorator) class can be put in the place of the component class. Because inheritance allows us that base class reference can hold the child object and decorator is child to component. Hence we can retain the benefit of inheritance with the help of decorator design pattern.  

Implementations within .net and JAVA  framework 

Decorator pattern is implemented in java IO library. If you understand the concept of decorator design patterns then one can realize different classes’ as wrappers and component. In this way it become extremely easier to implement can easily utilize the java IO library. 

 In .net it seems like the streaming library uses decorator pattern but there is a difference.  

 

In .net class diagram for IO library FileStream and NetworkStream are component classes where as BinaryReader and BinaryWriter acts as the wrapper classes. Wrapper can add new functionality component at run-time since we pass the object of component during run-time.  

The difference is that BinaryReader wraps FileStream and NetworkStream but it does not extend the base stream class. It simply contains the stream. This looks good because no one wants to wrap BinaryWriter and BinaryReader together and there is no need for type matching.  

Conclusion 

 In this article I explain the decorator pattern in a very simplified form as well as briefly describe its implementation in java and .net framework. 

References 

Book "Design Patterns: Elements of Reusable Object-oriented Software" by Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides .

 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

muhammadumairomee
Software Developer (Senior)
Pakistan Pakistan
Graduated in 2008 as a software engineer. I am primarily working on C# and .net. I also have developed project using Java and C++. I have work on data acquisition systems, real time displays, parallel processing, telemetry systems, geographical Information system (GIS), web development, database development, interfacing and several other projects during my career. My future interests are distributed computing, design patterns and parallel computing.
 
I love to watch good movies, playing squash and a hobbyist programmer.
Follow on   Twitter   LinkedIn

Comments and Discussions

 
GeneralMy vote of 1 PinmemberJason Storey19-Dec-13 5:11 
GeneralRe: My vote of 1 Pinmembermuhammadumairomee19-Dec-13 6:16 
GeneralMy vote of 2 PinmemberOshtri Deka19-Dec-13 0:45 
GeneralRe: My vote of 2 Pinmembermuhammadumairomee19-Dec-13 6:17 
QuestionI am not voting, but... PinprofessionalPaulo Zemek15-Dec-13 17:12 
AnswerRe: I am not voting, but... Pinmembermuhammadumairomee15-Dec-13 19:47 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web04 | 2.8.140905.1 | Last Updated 15 Dec 2013
Article Copyright 2013 by muhammadumairomee
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid