Decorator pattern a design pattern that allows behavior to be added to an individual object without affecting the behavior of other objects from the same class. Decorators provide a flexible alternative to subclass for extending functionality.
The decorator pattern is achieved by designing a new decorator class that wraps the original class, and providing additional functionality keeping class methods signature intact.
The basic steps as follows:
- Subclass “Component” class into a “Decorator” class
- Pass a Component to the Decorator constructor
- In the ConcreteDecorator class, override Component method(s).
Here is one example to demonstrate Decorator pattern implementation and usage.
Create interface (car)
1 2 3 4 5 6 7 |
package net.tecbar.designpattern.decorator; public interface Car { void upgrade(); } |
Concrete classes to implements the interface
1 2 3 4 5 6 7 8 9 10 11 |
package net.tecbar.designpattern.decorator; public class Acura implements Car { @Override public void upgrade() { System.out.println("base model Acura TLX"); } } |
1 2 3 4 5 6 7 8 9 10 11 |
package net.tecbar.designpattern.decorator; public class BMW implements Car { @Override public void upgrade() { System.out.println("base model BMW 328i"); } } |
Create abstract decorator class implementing the Car interface
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
package net.tecbar.designpattern.decorator; public abstract class CarDecorator implements Car { private Car car; public CarDecorator(Car car) { this.car = car; } @Override public void upgrade() { car.upgrade(); } } |
Create concrete decorator class extending the CarDecorator class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
package net.tecbar.designpattern.decorator; public class CarNavigationDecorator extends CarDecorator { public CarNavigationDecorator(Car car) { super(car); } public void upgrade() { super.upgrade(); System.out.println(" - Add GPS navigation system upgrade"); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
package net.tecbar.designpattern.decorator; public class CarTireDecorator extends CarDecorator { public CarTireDecorator(Car car) { super(car); } public void upgrade() { super.upgrade(); System.out.println(" - upgrade to 21 inch tires"); } } |
Decorate Cars (upgrade)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
package net.tecbar.designpattern.decorator; public class DecoratorDemo { public static void main(String[] args) { Car car = new CarTireDecorator(new CarNavigationDecorator(new BMW())); car.upgrade(); System.out.println(""); Car car2 = new CarNavigationDecorator(new Acura()); car2.upgrade(); } } |
Output
1 2 3 4 5 6 7 8 |
base model BMW 328i - Add GPS navigation system upgrade - upgrade to 21 inch tires base model Acura TLX - Add GPS navigation system upgrade |
Pingback: Software Design Patterns