Decorator Pattern
Author: Deron Eriksson
Description: This Java tutorial describes the decorator pattern, a structural design pattern.
Tutorial created using: Windows Vista || JDK 1.6.0_11 || Eclipse JEE Ganymede SR1 (Eclipse 3.4.1)


Page: < 1 2

(Continued from page 1)

The DecoratorDemo class demonstrates the decorator design pattern. First, a LivingAnimal object is created and is referenced via the Animal reference. The describe() method is called. After this, we wrap the LivingAnimal in a LegDecorator object and once again call describe. We can see that legs have been added. After that, we wrap the LegDecorator in a WingDecorator, which adds wings to our animal. Later, we wrap the animal in two GrowlDecorators. From the describe() output, we can see that two growl messages are displayed since we wrapped the animal twice.

DecoratorDemo.java

package com.cakes;

public class DecoratorDemo {

	public static void main(String[] args) {

		Animal animal = new LivingAnimal();
		animal.describe();

		animal = new LegDecorator(animal);
		animal.describe();

		animal = new WingDecorator(animal);
		animal.describe();

		animal = new GrowlDecorator(animal);
		animal = new GrowlDecorator(animal);
		animal.describe();
	}

}

The console output is shown here.

Console Output


I am an animal.

I am an animal.
I have legs.
I can dance.

I am an animal.
I have legs.
I can dance.
I have wings.
I can fly.

I am an animal.
I have legs.
I can dance.
I have wings.
I can fly.
Grrrrr.
Grrrrr.

In this example, we just used the Animal reference to refer to the objects. Using this approach, we could only access the shared operations of the Animal interface (ie, the describe() method). Instead of referencing this interface, we could have referenced the concrete decorator class. This would have exposed the unique functionality of the concrete decorator.

Page: < 1 2


Related Tutorials: