Powered by Blogger.

Decorator Design Pattern with an Example

>> Monday, May 30, 2011

Definition:
               Attach additional responsibilities or functions to an object dynamically or statically. Also known as Wrapper.
Where to use & benefits:
  1. Provide an alternative to subclassing.
  2. Add new function to an object without affecting other objects.
  3. Make a responsibility easily added and removed dynamically.
  4. More flexibility than static inheritance.
  5. Transparent to the object.
  6. Related patterns include  
Decorative Design Pattern with Example_JavabynataraJ
  •  Adapter pattern, which provides a different interface to the object it adapts, whereas a decorator changes an object's responsibilities,
  • Proxy pattern, which controls access to the object, whereas a decorator focuses on adding new functions to an object,
  • Composite pattern, which aggregates an object, whereas a decorator adds additional responsibilities to an object, and
  • Strategy pattern, which changes the guts of an object, whereas a decorator changes the skin of an object.
  • Facade pattern, which provides a way of hiding a complex class, whereas a decorator adds function by wrapping a class. 
Example on DecoratorDesignPattern :

A JScrollPane object can be used to decorate a JTextArea object or a JEditorPane object. A window can be decorated with different borders like BevelBorder, CompoundBorder, EtchedBorder TitledBorder etc. These border classes working as decorators are provided in Java API.

Design Patterns in Java(TM) can be used in a non-visual fashion. For example, BufferedInputStream, DataInputStream, and CheckedInputStream are decorating objects of FilterInputStream class. These decorators are standard Java API classes.

To illustrate a simple decorator pattern in non-visual manner, we design a class that prints a number. We create a decorator class that adds a text to the Number object to indicate that such number is a random number. Of course we can subclass the Number class to achieve the same goal. But the decorator pattern provides us an alternative way.
import java.util.Random;
class Number {
   public void print() {
       System.out.println(new Random().nextInt());
   }
}

class Decorator {
    public Decorator() {
        System.out.print("Random number: ");//add a description to the number printed
        new Number().print();
    }
}

class SubNumber extends Number{
    public SubNumber() {
       super();
       System.out.print("Random number: ");
       print();
    }
}

class Test {
    public static void main(String[] args) {
        new Decorator();
        new SubNumber();
    }
}

The Output of the above program:


java Test
Random number: 145265744
Random number: 145265755

Reference books on Design Patterns:

Related Posts Plugin for WordPress, Blogger...
© javabynataraj.blogspot.com from 2009 - 2022. All rights reserved.