Java Design Patterns Tutorial - Java Design Pattern - Decorator Pattern








Decorator pattern adds new functionality an existing object without chaining its structure.

It is a structural pattern as it acts as a wrapper to existing class.

Decorator pattern creates a decorator class to wrap the original class and provides additional functionality.

Example

interface Printer {
   void print();/*from   ww w . j a v  a  2 s . c o m*/
}
class PaperPrinter implements Printer {
   @Override
   public void print() {
      System.out.println("Paper Printer");
   }
}
class PlasticPrinter implements Printer {
   @Override
   public void print() {
      System.out.println("Plastic Printer");
   }
}
abstract class PrinterDecorator implements Printer {
   protected Printer decoratedPrinter;
   public PrinterDecorator(Printer d){
      this.decoratedPrinter = d;
   }
   public void print(){
      decoratedPrinter.print();
   }  
}
class Printer3D extends PrinterDecorator {
   public Printer3D(Printer decoratedShape) {
      super(decoratedShape);    
   }
   @Override
   public void print() {
     System.out.println("3D.");
     decoratedPrinter.print();         
   }
}
public class Main {
   public static void main(String[] args) {
      Printer plasticPrinter = new PlasticPrinter();
      Printer plastic3DPrinter = new Printer3D(new PlasticPrinter());
      Printer paper3DPrinter = new Printer3D(new PaperPrinter());
      plasticPrinter.print();
      plastic3DPrinter.print();
      paper3DPrinter.print();
   }
}

The code above generates the following result.