Decorator Pattern

Decorator Pattern

Decorator pattern is technique where existing object behavior to be added dynamically or in another word when we change object behavior at runtime which is also called in java runtime polymorphism.

This decorator pattern is another approach to sub classing. When we do sub classing means it adds behavior at compile time and change takes affects to all instances of original class. Decorating object provides new behavior of the object at runtime of each individual objects and this modification or difference becomes important when we have several independent techniques of extending existing functionality of the objects. For example Input/output streams implementations in java framework incorporate decorator pattern.

Below example will show you how to use decorator pattern (We will use apartment scenario)

  • Apartment Interface
public interface Apartment {
	int size();
	String getSizeDescription();

}

 

  • Implementation of a simple Apartment without adding anything
public class SimpleApartment implements Apartment{

	@Override
	public int size() {
		return 700;
	}

	@Override
	public String getSizeDescription() {
		return "Simple 700 sqft. Apartment";
	}

}

 

  • Below abstract class implements Apartment interface and adds one abstract function to decorate apartment
public abstract class ApartmentDecorator implements Apartment{

	//create abstract method to add furniture in apartment
	abstract String Furniture();

}

 

  • Now create concrete class FurnishedApartment by extending Apartment Decorator to decorate apartment
public class FurnishedApartment extends ApartmentDecorator {

	@Override
	public int size() {
		return 800;
	}

	@Override
	public String getSizeDescription() {
		return "800 sqft.";
	}

	@Override
	String Furniture() {
		return "Sofa set, Dining table, Marble Kitchen top and whole area carpeted";
	}	

}

 

  • Below is test program:
public class ApartmentDecoratorTest {

	public static void main(String[] args) {
		//Get simple apartment and it's description
		SimpleApartment simpleApartment=new SimpleApartment();
		System.out.println("Size: "+simpleApartment.size()+
				" Size Description:"+simpleApartment.getSizeDescription());

		//Get Furnished apartment and it's description
		FurnishedApartment furnishedApartment=new FurnishedApartment();
		System.out.println("Size: "+furnishedApartment.size()+
				" Size Description:"+furnishedApartment.getSizeDescription()+
				"Furniture details: "+furnishedApartment.Furniture());

	}

}

 

  • That’s it. Below is list of all design patterns link:

Creational Patterns:

Structural Patterns:

Behavioral Patterns:

Leave a Reply

Your email address will not be published. Required fields are marked *