Structural Design Pattern: Decorator Pattern - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Random Posts

Structural Design Pattern: Decorator Pattern

Share This
The Decorator Pattern involves dynamically adding flexible new responsibilities to an object. The Decorator Pattern uses composition rather than inheritance to dynamically enhance the capabilities of an object.

The Decorator Pattern is commonly referred to as the Wrapper Pattern.

The advantage of the Decorator Pattern is its ability to dynamically add new behaviors or functionalities to an object without modifying its structure.

It offers more versatility than static inheritance. The extensibility of the object is improved as changes are implemented through the creation of new classes. It streamlines the coding process by enabling the development of specific functionalities through focused classes, rather than putting all of the behavior directly into the object.

Implementation of the Decorator Pattern

  • When you desire to seamlessly and flexibly assign additional duties to objects without impacting other items. 
  • When you desire to allocate additional responsibilities to an object that you may potentially modify in the future. 
  • Sub-classing is no longer a useful method for extending functionality.

Source code of Printer.java
package com.t4b.test.java.dp.sp.dp; interface Printer { void print(); }
Source code of PaperPrinter.java
package com.t4b.test.java.dp.sp.dp; class PaperPrinter implements Printer { @Override public void print() { System.out.println("Paper Printer"); } }
Source code of PlasticPrinter.java
package com.t4b.test.java.dp.sp.dp; class PlasticPrinter implements Printer { @Override public void print() { System.out.println("Plastic Printer"); } }
Source code of PrinterDecorator.java
package com.t4b.test.java.dp.sp.dp; abstract class PrinterDecorator implements Printer { protected Printer decoratedPrinter; public PrinterDecorator(Printer d) { this.decoratedPrinter = d; } public void print() { decoratedPrinter.print(); } }
Source code of Printer3D.java
package com.t4b.test.java.dp.sp.dp; class Printer3D extends PrinterDecorator { public Printer3D(Printer decoratedShape) { super(decoratedShape); } @Override public void print() { System.out.println("3D."); decoratedPrinter.print(); } }
Source code of TestMain.java
package com.t4b.test.java.dp.sp.dp; public class TestMain { 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(); } }

Happy Exploring!

No comments:

Post a Comment