Skip to content

Instantly share code, notes, and snippets.

@mitulmanish
Created April 25, 2016 15:28
Show Gist options
  • Save mitulmanish/e5e5ef1f6f58f563e5e58117f181e858 to your computer and use it in GitHub Desktop.
Save mitulmanish/e5e5ef1f6f58f563e5e58117f181e858 to your computer and use it in GitHub Desktop.
Decorator Pattern in Java
package com.company;
interface Coffee{
Double getCost();
String getIngredients();
}
class SimpleCoffee implements Coffee {
@Override
public Double getCost() {
return 3.0;
}
@Override
public String getIngredients() {
return "Coffee";
}
}
class CoffeeDecorator implements Coffee{
Coffee decoratedCoffee;
String ingredientSeperator = " , ";
CoffeeDecorator(Coffee decoratedCoffee) {
this.decoratedCoffee = decoratedCoffee;
}
@Override
public Double getCost() {
return decoratedCoffee.getCost();
}
@Override
public String getIngredients() {
return decoratedCoffee.getIngredients();
}
}
class Milk extends CoffeeDecorator{
public Milk(Coffee decoratedCoffee) {
super(decoratedCoffee);
}
@Override
public Double getCost() {
return super.getCost() + 0.7;
}
@Override
public String getIngredients() {
return super.getIngredients() + ingredientSeperator + "Milk";
}
}
class WhipCoffee extends CoffeeDecorator{
public WhipCoffee(Coffee decoratedCoffee) {
super(decoratedCoffee);
}
@Override
public Double getCost() {
return super.getCost() + 1.0;
}
@Override
public String getIngredients() {
return super.getIngredients() + ingredientSeperator + "Whip";
}
}
public class Main {
public static void main(String[] args) {
// write your code here
Coffee simpleCoffee = new SimpleCoffee();
System.out.println("Cost: " + simpleCoffee.getCost() + " Ingredients: " + simpleCoffee.getIngredients());
simpleCoffee = new Milk(simpleCoffee);
System.out.println("Cost: " + simpleCoffee.getCost() + " Ingredients: " + simpleCoffee.getIngredients());
simpleCoffee = new WhipCoffee(simpleCoffee);
System.out.println("Cost: " + simpleCoffee.getCost() + " Ingredients: " + simpleCoffee.getIngredients());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment