Java Design Patterns .

Java Design Patterns Decorator

Decorator (aka Wrapper) Overview

One class takes in another class, both of which extend the same abstract class, and adds functionality. - the abstract base class

public abstract class Tea {  
   boolean teaIsSteeped; 
   public abstract void steepTea();
To download source right-click here and "Save As...". - the decoratee

public class TeaLeaves extends Tea {  
   public TeaLeaves() {
       teaIsSteeped = false;
   public void steepTea() {
       teaIsSteeped = true;
       System.out.println("tea leaves are steeping");
To download source right-click here and "Save As...". - the decorator

import java.util.ArrayList;
import java.util.ListIterator;

public class ChaiDecorator extends Tea { private Tea teaToMakeChai; private ArrayList chaiIngredients = new ArrayList(); public ChaiDecorator(Tea teaToMakeChai) { this.addTea(teaToMakeChai); chaiIngredients.add("bay leaf"); chaiIngredients.add("cinnamon stick"); chaiIngredients.add("ginger"); chaiIngredients.add("honey"); chaiIngredients.add("soy milk"); chaiIngredients.add("vanilla bean"); }

private void addTea(Tea teaToMakeChaiIn) { this.teaToMakeChai = teaToMakeChaiIn; } public void steepTea() { this.steepChai(); }

public void steepChai() { teaToMakeChai.steepTea(); this.steepChaiIngredients(); System.out.println("tea is steeping with chai"); } public void steepChaiIngredients() { ListIterator listIterator = chaiIngredients.listIterator(); while (listIterator.hasNext()) { System.out.println(((String)( + " is steeping"); } System.out.println("chai ingredients are steeping"); } }
To download source right-click here and "Save As...". - testing the decorator

class TestChaiDecorator {            
   public static void main(String[] args) {
       Tea teaLeaves = new TeaLeaves();
       Tea chaiDecorator = new ChaiDecorator(teaLeaves);
To download source right-click here and "Save As...".

Test Results

tea leaves are steeping
bay leaf is steeping
cinnamon stick is steeping
ginger is steeping
honey is steeping
soy milk is steeping
vanilla bean is steeping
chai ingredients are steeping
tea is steeping with chai


UML for Decorator


Portland Pattern Repository
Design Patterns by Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides
Java Design Patterns - A Tutorial by James W. Cooper
Sign in to be the first to comment on Java Design Patterns Decorator.