Pin It

Decorator Design Pattern in Java


What is Decorator Design Pattern in Java.

The formal definition of the Decorator pattern from the GoF book (Design Patterns: Elements of Reusable Object-Oriented Software, 1995, Pearson Education, Inc. Publishing as Pearson Addison Wesley) says you can,

"Attach additional responsibilities to an object dynamically. Decorators
provide a flexible alternative to subclassing for extending functionality."


Let's say we have a Pizza and we want to decorate it with toppings such as Chicken Masala, Onion and Mozzarella Cheese. Let's see how to implement it in Java ...

Program to demonstrate how to implement Decorator Design Pattern in Java.

1. Pizza.java

package com.hubberspot.designpattern.structural.decorator;

public class Pizza {

    public Pizza() {
        
    }
    
    public String description(){
        return "Pizza";
    }    
}



2. PizzaToppings.java
package com.hubberspot.designpattern.structural.decorator;

public abstract class PizzaToppings extends Pizza {

    public abstract String description();
    
}



3. ChickenMasala.java

package com.hubberspot.designpattern.structural.decorator;

public class ChickenMasala extends PizzaToppings {

private Pizza pizza;
    
    public ChickenMasala(Pizza pizza) {
        this.pizza = pizza;
    }
    
    @Override
    public String description() {
        return pizza.description() + " with chicken masala, ";
    }

}



4. Onion.java

package com.hubberspot.designpattern.structural.decorator;

public class Onion extends PizzaToppings {

    private Pizza pizza;
    
    public Onion(Pizza pizza) {
        this.pizza = pizza;
    }
    
    @Override
    public String description() {
        return pizza.description() + "onions, ";
    }

}



5. Mozzarella.java

package com.hubberspot.designpattern.structural.decorator;

public class MozzarellaCheese extends PizzaToppings {

    private Pizza pizza;
    
    public MozzarellaCheese(Pizza pizza) {
        this.pizza = pizza;
    }
    
    @Override
    public String description() {
        return pizza.description() + "and mozzarella cheese.";
    }
}




6. TestDecorator.java

package com.hubberspot.designpattern.structural.decorator;

public class TestDecorator {

    public static void main(String[] args) {
        
        Pizza pizza = new Pizza();
        
        pizza = new ChickenMasala(pizza);
        pizza = new Onion(pizza);
        pizza = new MozzarellaCheese(pizza);
        
        System.out.println("You're getting " + pizza.description());

    }

}


Output of the program : 

 
Please Give Us Your 1 Minute In Sharing This Post!
SOCIALIZE IT →
FOLLOW US →
SHARE IT →
Related Posts Plugin for WordPress, Blogger...

Post your related queries below ...

comments powered by Disqus
Powered by Blogger.
 
© 2012 Learn Java by Examples Template by Hubber Spot