Thursday, March 27, 2008

Decorator pattern with Simple Example

Decorator


Definition

Attach additional responsibilities or functions to an object dynamically or statically. Also known as Wrapper.

Where to use & benefits

  • Provide an alternative to subclassing.
  • Add new function to an object without affecting other objects.
  • Make a responsibility easily added and removed dynamically.
  • More flexibility than static inheritance.
  • Transparent to the object.

Example

Decorator pattern 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 Test {
    public static void main(String[] args) {
        new Decorator();
        }
}
java Test
Random number: 145265744

 

No comments:

Post a Comment