Decorator pattern

Decorator pattern

software_development

The decorator pattern is a design pattern used to add new behaviors to objects without modifying their classes.

A practical example

Let’s say we have a Product interface that has a method that returns the cost of the product itself. We also have a Pasta class that implements Product.


interface Product {
	public Double getPrice();	
}

class Pasta implements Product {
	public Double getPrice() {
		return this.price;
	}
}

Now, we want to always add the VAT to the products price without changing the code of the Pasta class. Let’s apply the decorator pattern.


class ProductWithVAT implements Product() {
	private Product product;

	public ProductWithVAT(Product product) {
		this.product = product;
	}

	public Double getPrice() {
		return product.getPrice() + (product.getPrice() * 0.22);
	}	
}

The ProductWithVAT class implements the Product interface and also takes another Product as an argument of its constructor. When returning the price, it adds the VAT to the price of the product that we passed him. When we want to use this classes we can simply do this:


{
	[...]

	Pasta pasta = new Pasta();
	ProductWithVAT pastaVAT = new ProductWithVAT(pasta);
	return pastaVAT.getPrice();
}

Related News