Java decorator design pattern

Java decorator design pattern comes under structural design patterns and it provides the facility to add additional responsibilities to an existing object without altering its structure. It uses composition to extend the facility to an existing objects.

Main advantage of decorator is to increase the existing functionality of an object without making any changes in it.

Let’s discuss decorator design pattern with the below example. We have a MediaPlayer as an interface. We provide basic implementation of this interface as BasicMediaPlayer. Next step is to create a MediaPlayerDecorator which will implements the MediaPlayer interface. Next we will create a concrete decorator which will add the additional functionality to MediaPlayerDecorator.

Example

MediaPlayer.java

package com.w3schools;
 
public interface MediaPlayer {
	public void assemble();
}

BasicMedialayer.java

package com.w3schools;
 
public class BasicMedialayer implements MediaPlayer {
	@Override
	public void assemble() {
		System.out.println("Basic media player");
	}
}

MediaPlayerDecorator.java

package com.w3schools;
 
public class MediaPlayerDecorator implements MediaPlayer {
	protected MediaPlayer mediaPlayer;
 
	public MediaPlayerDecorator(MediaPlayer mediaPlayer){
		this.mediaPlayer=mediaPlayer;
	}
 
	@Override
	public void assemble() {
		this.mediaPlayer.assemble();		
	}
}

MP4Player.java

package com.w3schools;
 
public class MP4Player extends MediaPlayerDecorator {
	public MP4Player(MediaPlayer mediaPlayer) {
		super(mediaPlayer);
	}
 
	@Override
	public void assemble() {
		super.assemble();
		System.out.println("Adding functionality to run MP4 files.");		
	}
}

VLCPlayer.java

package com.w3schools;
 
public class VLCPlayer extends MediaPlayerDecorator {
	public VLCPlayer(MediaPlayer mediaPlayer) {
		super(mediaPlayer);
	}
 
	@Override
	public void assemble() {
		super.assemble();
		System.out.println("Adding functionality to run VLC files.");		
	}
}

DecoratorPatternTest.java

package com.w3schools;
 
public class DecoratorPatternTest {
	public static void main(String args[]){
		MediaPlayer vLCPlayer = new VLCPlayer(new BasicMedialayer());
		vLCPlayer.assemble();
		System.out.println();
 
		MediaPlayer decoratedVLCPlayer = new VLCPlayer(new MP4Player(new BasicMedialayer()));
		decoratedVLCPlayer.assemble();
	}
}

Output

Basic media player
Adding functionality to run VLC files.
 
Basic media player
Adding functionality to run MP4 files.
Adding functionality to run VLC files.