Start networking and exchanging professional insights

Register now or log in to join your professional community.

Follow

Where do you use "Decorator Pattern" while developing software?

user-image
Question added by Tuna Ozkasap , Senior Technology Consultant , SAP
Date Posted: 2014/01/22
Muhammad Junaid
by Muhammad Junaid , Software Architect Java , NADRA

Its an alternative way of extending the behaviour of a Class. Usually we would inherit a Class and over-ride its methods but this pattern tells us how to extend the behaviour by using composition.

A good example is the Java Buffered IO classes. It extend the behaviour of IO writter classes by adding buffering behaviour. It means ecah time you call write(..) fucntion of a Buffered IO Object, it will not write to disk immediately but the data will be stored in memory and after some threshold is reached it will be written to disk. This way effeciency of IO opertions is increased.

So we could have inherited the IO writers to achieve it but instead in Java they have used Decorator pattern. The Buffered class which is the decorator contians a instance variable of the IO class type which it is decorating. When write(..) of Decorator is called, it will keep on using memory biffer and finally it will call the write(..) of the contained IO Object.

 

Reason for choosing this approach can be that we do not want to create a complex inheritence tree, each time we need a new functionality. As in Java Multiple inheritence is not allowed so its a good way of filling that gap.

 

 

More Questions Like This

Do you need help in adding the right keywords to your CV? Let our CV writing experts help you.