BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Design Patterns
.NET 1.1+

Decorator Design Pattern

The decorator pattern is a design pattern that extends the functionality of individual objects by wrapping them with one or more decorator classes. These decorators can modify existing members and add new methods and properties at run-time.

Testing the Decorators

To test the decorators we can use a new console application. Add the code shown below to the Main method then execute the program. The test code creates a new vehicle and outputs its details to the console. Next, a special offer decorator is added to the car and the modified pricing and laps permitted is outputted.

To demonstrate the second decorator, a Hireable object is use to wrap to the car object and the Hire method is called. This demonstrates that the Hire method has been added to the vehicle at run-time. Finally, the vehicle with a special offer applied is wrapped with a Hireable decorator and the Hire method is called. The output of this call demonstrates the stacking of two decorators on a single object.

NB: The output may differ from that displayed as the formatting will show your preferred currency symbol.

// Basic vehicle
Ferrari360 car = new Ferrari360();

Console.WriteLine("Base price is {0:c} for {1} laps.", car.HirePrice, car.HireLaps);

// Special offer
SpecialOffer offer = new SpecialOffer(car);
offer.DiscountPercentage = 25;
offer.ExtraLaps = 2;

Console.WriteLine("Offer price is {0:c} for {1} laps.", offer.HirePrice, offer.HireLaps);

// Hire for basic vehicle
Hireable hire1 = new Hireable(car);
hire1.Hire("Bob");

// Hire for vehicle with special offer
Hireable hire2 = new Hireable(offer);
hire2.Hire("Bill");

/* OUTPUT

Base price is £100.00 for 10 laps.
Offer price is £75.00 for 12 laps.
Ferrari 360 hired by Bob at a price of £100.00 for 10 laps.
Ferrari 360 hired by Bill at a price of £75.00 for 12 laps.

*/
15 February 2009