Decorator Design Pattern Using Java Decorator Design Pattern Using Java

Decorator design pattern is used to add a new feature on the existing object by wrapping it with a decorator class.

In this example, we will first create an interface Window interface and its implementation BasicWindow

interface Window {
    public String draw();
}

class BasicWindow implements Window {

    @Override
    public String draw() {
        return "Basic Window";
    }
}

Next, we want to decorate this Window with some border and scroll bar. We need a wrapper class for this which can wrap Window to add new features. For this, we create a class WindowDecorator which takes Window as constructor argument and also override draw() method to add new feature.

class WindowDecorator implements Window {

    protected Window window;

    public WindowDecorator(Window window) {
        this.window = window;
    }

    @Override
    public String draw() {
        return window.draw();
    }
}

We’ll now implement our wrapper class WindowDecorator and create two decorator classes BorderDecorator and ScrollDecorator. These decorators override draw() method to add new features like border and scroll bar.

class BorderDecorator extends WindowDecorator {

	public BorderDecorator(Window window) {
		super(window);
	}

	@Override
	public String draw() {
		return window.draw() + addBorder();
	}

	public String addBorder() {
		return " with Border";
	}
}

class ScrollDecorator extends WindowDecorator {

	public ScrollDecorator(Window window) {
		super(window);
	}

	@Override
	public String draw() {
		return window.draw() + addScroll();
	}

	public String addScroll() {
		return " and Scroll Bar";
	}
}

Let’s test our decorator classes

@Test
public void testDecorators() {
  
  Window basicWindow = new BasicWindow();
  assertEquals(basicWindow.draw(), "Basic Window");
  
  Window borderWindow = new BorderDecorator(basicWindow);
  assertEquals(borderWindow.draw(), "Basic Window with Border");

  Window borderWindowScrollable = new ScrollDecorator(borderWindow);
  assertEquals(borderWindowScrollable.draw(), "Basic Window with Border and Scroll Bar");
}

Few points from test:

  1. We have created a basicWindow object and decorated it using BorderDecorator
  2. Next we further decorated it using ScrollDecorator
  3. We can add as many as decorators at runtime to add new features to object.