Decorator Design Pattern implementation in Java

Posted By : Pavan Kumar | 26-May-2020

Java

Loading...

1. Why do we need to use Design Patterns:- The main aim of design patterns, as per Gang of Four(GoF), is to resolve complex problems to design flexible, easy, and reusable Softwares.

2. Structural Design Pattern:- In the field of Software Engineering, the structural design patterns are of those design patterns which make design easy by identifying a better way to maintain the relationship between entities.

In other words, this kind of design patterns deals with structures and relationship among them.

3. The Decorator Design Pattern:- The decorator design pattern comes into the category of structural design patterns. It allows behavior to be added to a particular object, either statically or dynamically, without affecting the behavior of other objects of the same class.

In other words, the decorator pattern allows adding behavior to an object dynamically without affecting the other objects of the same class.

4. Need of Decorator Design Pattern:- In today's era of object-oriented programming, inheritance means reusability of code by extending/implementing a class/interface but in some scenarios, it is not good to use. That's why we need decorator design pattern.

5. The Decorator Design Pattern Implementation:- It implements many classes(s) and interface(s). The decorator’s implementation is mentioned below.

5.1. We will create one interface which consists of many methods as per our need. In this example, the interface named is Bike and Bike interface has two methods out of which one for getting the description and the other for getting the cost of the bike.


public interface Bike{
   
    String getDescription();
    double getPrice();
}

5.2.Now we will createHondaBikeclass which implements Bike interface.

  public class HondaBike implements Bike{
  
   public String getDescription(){
      return "Bike";
   }

   public double getPrice(){
      return 50000.00;
   }
}

5.3. A Bike decorator is created to be implemented by all kinds of bikes which have any kind of topping accept honda bike. It overrides both methods and any object of its sub-class thus created, passes an object of honda bike class in its constructor through super keyword.

public class BikeDecorator implements Bike{
   
   Bike bike;

   public BikeDecorator(Bike bike){
     this.bike=bike;
   }      

   public String getDescription(){
      return this.bike.getDescription();
   }

   public double getPrice(){
      return this.bike.getPrice();
   }
}

5.4. Now, let's focus on the implementation class(s) of the bike decorator class.

5.4.1. This class overrides both the methods as per the need of bajaj bike properties and passes honda bike class object to its superclass.

public class BajajBike extends BikeDecorator{
  
   public BajajBike(Bike bike){
      super(bike);
   }

   public String getDescription(){
     return "Bajaj "+this.bike.getDescription();
   }

   public double getPrice(){
     return 200+this.bike.getPrice();
   }
}

5.4.2.This class overrides both the methods as per the need of yamaha bike properties and passes honda bike class object to its superclass.

public class YamahaBike extends BikeDecorator{
  
   public YamahaBike(Bike bike){
      super(bike);
   }

   public String getDescription(){
     return "Yamaha "+this.bike.getDescription();
   }

   public double getPrice(){
     return 150+this.bike.getPrice();
   }
}

5.4.2. This class overrides both the methods as per the need of Yamaha bike properties and passes honda bike class object to its superclass.

public class HeroBike extends BikeDecorator{
 
   public HeroBike(Bike bike){
     super(bike);
   }      

   public String getDescription(){
      return "Hero "+this.bike.getDescription();
   }

   public double getPrice(){
      return 50+this.bike.getPrice();
   }
}

5.5. This is the class that demonstrates the demo of the decorator design pattern. It does the following things.

i> It displays bike menu.

ii> It reads user's choice and accordingly creates bike class object.

iii> By using a created object, it gets the description and price of bike as well as calculates total amount.

iv> If the user is done with his/her order, then it shows the total amount to be paid and displays a message- thanks for visiting this showroom.

import java.util.Scanner;

public class DecoratorDesignPattern{
   
   static Scanner scanner=new Scanner(System.in);
   static int choice;
   static double totalAmount=0;

   public static void main(String a[]){
 
      System.out.println("==========Welcome to Bike Showroom==========");
      System.out.println("1. Honda Bike");
      System.out.println("2. Bajaj Bike");
      System.out.println("3. Yamaha Bike");
      System.out.println("4. Hero Bike");
      System.out.println("5. Exit");
      do{
		choice=scanner.nextInt();
		switch(choice){
			case 1:
				Bike bike=new HondaBike();
				String hondaBikeDescription=bike.getDescription();
				System.out.println("Description: "+hondaBikeDescription);
				double hondaBikePrice=bike.getPrice();
				System.out.println("Price: "+hondaBikePrice);
                                totalAmount=totalAmount+hondaBikePrice;
                                System.out.println("Total Amount: "+totalAmount);
				break;
			case 2: 
				BajajBike bajajBike=new BajajBike(new HondaBike());
			        String bajajBikeDescription=bajajBike.getDescription();
			        System.out.println("Description: "+bajajBikeDescription);
			        double bajajBikePrice=bajajBike.getPrice();
			        System.out.println("Price: "+bajajBikePrice);
				totalAmount=totalAmount+bajajBikePrice;
                                System.out.println("Total Amount: "+totalAmount);
				break;
			case 3:
				YamahaBike yamahaBike=new YamahaBike(new HondaBike());
			        String yamahaBikeDescription=yamahaBike.getDescription();
			        System.out.println("Description: "+yamahaBikeDescription);
			        double yamahaBikePrice=yamahaBike.getPrice();
			        System.out.println("Price: "+yamahaBikePrice);
     				totalAmount=totalAmount+yamahaBikePrice;
                                System.out.println("Total Amount: "+totalAmount);
				break;
			case 4:
				HeroBike heroBike=new HeroBike(new HondaBike());
			        String heroBikeDescription=heroBike.getDescription();
			        System.out.println("Description: "+heroBikeDescription);
			        double heroBikePrice=heroBike.getPrice();
			        System.out.println("Price: "+heroBikePrice);
     				totalAmount=totalAmount+heroBikePrice;
                                System.out.println("Total Amount: "+totalAmount);
				break;
			default: 
                                System.out.println("Total Amount to Pay: "+totalAmount);
				System.out.println("Thank You for visiting Bike Shop.");
				break;
			
		}
      } while(choice!=5);
   }
}

6. Use(s):-It can be used where there is the need for adding behavior to an object dynamically.
6.1.As same as used in bike example above.
6.2.Browser window.

Decorator patterns allow a user to dynamically add new functionality to an existing object without altering the behavior of other existing objects in the same class. It simply provides a wrapper to the existing class. We are a Java Development Company with the aim of providing industrial-grade development services to enterprises to facilitate efficiency through automation. Our developers have about a decade’s worth experience of developing ERP software and its application customized to use cases. Get in touch with us NOW to avail of our Java Development Services.