Select Page

Decorator

Decorator

Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.

Source Code

/**  * Defines the interface for objects that can have responsibilities added to the  * dynamically.  *   * @role __Component  */ public abstract class Component { 	/** 	 * Sample operation. 	 */ 	public abstract void doSomeStuff(); }  /**  * Defines an object to which additional responsibilities can be attached.  */  public class ConcreteComponent extends Component { 	/** @see patterns.gof.decorator.Component#doSomeStuff() */ 	public void doSomeStuff() { 		// provide implementation here 	} }  /**  * Adds responsibilities to the component.  */  public class ConcreteDecorator extends Decorator { 	public ConcreteDecorator(Component decorateMe) { 		super(decorateMe); 	}  	/** 	 * Behavior added by decorator. 	 */ 	private void addedBehavior() { 		// some extra functionality goes here 	}  	public void doSomeStuff() { 		super.doSomeStuff(); 		addedBehavior(); 	} }  /**  * Maintains the reference to a Component object and defines an interface that  * conforms to Component's interface  *   * @role __Decorator  */  public abstract class Decorator extends Component { 	/** reference to the decorated component */ 	protected Component component;  	/** 	 * @param decorateMe 	 *            component to decorate 	 */ 	public Decorator(Component decorateMe) { 		this.component = decorateMe; 	}  	public void doSomeStuff() { 		component.doSomeStuff(); 	} } 

About The Author

I worked with various Insurances companies across Switzerland on online applications handling billion premium volumes. I love to continuously spark my creativity in many different and challenging open-source projects fueled by my great passion for innovation and blockchain technology.In my technical role as a senior software engineer and Blockchain consultant, I help to define and implement innovative solutions in the scope of both blockchain and traditional products, solutions, and services. I can support the full spectrum of software development activities, starting from analyzing ideas and business cases and up to the production deployment of the solutions.I'm the Founder and CEO of Disruptr GmbH.

Categories