Friday, November 1, 2019

Decorator Blueprint Pattern Inward Coffee Alongside Example

The Decorator blueprint Pattern is i of the famous Gang of Four (GOF) structural blueprint pattern, which provides a dynamic way of extending an object's functionality. It's unlike than the traditional way of adding novel functionality into an object using Inheritance, instead, it uses Composition which makes it flexible in addition to allows to add together novel functionalities at the run time, equally contrary to Inheritance, which adds new functionality at compile time. Because of this flexibility, Decorator is i of the darling patterns for many Java developer. Btw, similar many others object-oriented blueprint patterns, the decorator blueprint pattern is introduced past times the famous Gang of Four blueprint pattern book, almost ii decades ago. This way it's a time-tested way of adding novel functionalities into an object.

In this Java blueprint pattern tutorial, nosotros volition larn the Decorator blueprint pattern past times using it inward a Java example. This is the best way of learning blueprint pattern, followed y'all essay it yourself to apply inward similar scenarios. 

The decorator pattern is i of the pop blueprint patterns along amongst the Factory method pattern in addition to Singleton Pattern, in addition to y'all tin give notice meet it's usage fifty-fifty inward JDK itself. A duo of classes from the java.io bundle like BufferedInputStream, LineNumberInputStream are a practiced illustration of Decorator blueprint pattern inward Java. 

Btw, if y'all are novel into blueprint pattern world, thence I likewise advise y'all check The Java Design Patterns Masterclass which non alone covers Decorator pattern but likewise other GOF patterns. It was likewise late been updated to comprehend Java SE 8 implementation equally well.




Decorator Design Pattern inward Java

In gild to demo you, how to implement a Decorator pattern, allow me get-go explicate requirements. Do nosotros demand to create software for calculating the cost for a Sandwich, yummy... no? Since the client tin give notice customize a sandwich past times asking extra cheese or extra fillings, y'all likewise demand to include the cost of those items inward the terminal cost of Sandwich. 

Since this customization tin give notice vary a lot amid unlike customers in addition to offering from a shop, creating classes for unlike types of Sandwich amongst unlike fillings or extras like BrownBreadSandWithCheese or WhiteBreaSandwitchWithCheeseAndTomato volition simply clutter the code amongst lots of endless small-scale classes. 

Now this occupation looks a natural correspond for applying Decorator pattern because nosotros receive got a base of operations object Sandwich, which tin give notice survive decorated amongst extra cheese in addition to fillings. By using the Decorator pattern, y'all tin give notice extend the functionality of Sandwich class at runtime, based upon customer's request, which is impossible amongst Inheritance until y'all receive got a specific shape for every possible client request. 

This is likewise i of the reasons why Composition is preferred over Inheritance inward Object-oriented blueprint in addition to specially inward Java. 

Now, let's meet our shape structure, We receive got an abstract shape Sandwich, amongst abstract method price() in addition to a concrete implementation shape WhiteBreadSandwich, which cost $3.0

Now, inward gild to render extra cheese, which manifestly incurs extra cost, nosotros are going to utilization the Decorator blueprint pattern. We receive got a Decorator abstract class, which volition human activeness equally a base of operations for Decorators called SandwichDecorator, in addition to a concrete implementation of this equally CheeseDecorator.

SandwichDecorator extends Sandwich, to survive of the same type equally the original object, which is getting decorated. This is a critical requirement of Decorator pattern thence that a decorated object tin give notice stand upwards inward house of the original object similar it tin give notice survive passed when a method expects the original object. 

Decorator adds functionality earlier or later on delegating the chore to the original object, which way inward this illustration cost of a WhilteBreadSandwich with Cheese volition survive calculated past times the get-go calculating cost of WhiteBreadSandwich in addition to thence the cost of Cheese. 

Finally, I receive got a shape called SandwichMaker, which volition brand a delicious sandwich for y'all :) I hateful it volition examine the whole programme in addition to demonstrate how Decorator pattern adds novel functionality on the wing at runtime. 

I receive got likewise used BigDecimal to stand upwards for coin instead of double primitive to follow best practices suggested inward Effective Java. If y'all don't know why to read this Java error virtually using double to stand upwards for the price






UML diagram of Decorator Pattern

Here is the UML shape diagram of the decorator blueprint pattern. You tin give notice meet that nosotros receive got a Component interface, which is used to create ConcreteComponents. In our real-world example, Sandwich is a element interface in addition to WhiteBreadSandwich is a concrete component. 

Now if nosotros desire to add together an additional characteristic to the Component interface, nosotros create closed to other interface called Decorator, which inherit Component interface, this is rattling of import because it allows y'all to overstep an event of Decorator to whatsoever method which accepts an event of the Component interface. 

Now y'all tin give notice create an implementation of a decorator, which has both functionalities provided past times the original interface in addition to novel characteristic provided past times the decorator. This way y'all tin give notice add together novel features inward the existing shape hierarchy without modifying tried in addition to tested code. 

This is closed to other argue programmers country why the composition is meliorate than Inheritance, but if y'all desire to larn to a greater extent than virtually blueprint principles in addition to patterns, delight see Eclipse IDE, simply create a Java project, select that projection inward the bundle explorer in addition to re-create the code there, it volition automatically create correct packages in addition to Java classes. 


Sandwich.java import java.math.BigDecimal;  /**  * Base shape for all types of Sandwich, cost method is abstract because  * unlike sandwiches has unlike price.  *  * @author Javin Paul  */ public abstract class Sandwich {        protected String description = "Sandwich";           public String getDescription(){         return description;     }         public abstract BigDecimal price(); }   WhiteBreadSandWich.java import java.math.BigDecimal;  /**  * Influenza A virus subtype H5N1 Concrete implementation of abstract Sandwich class, which stand upwards for a WhiteBread  * Sandwich, whose cost is 3.0$.  *  * @author Javin Paul  */ public class WhiteBreadSandWich extends Sandwich {         public WhiteBreadSandWich(String desc){        description = desc;     }         @Override     public BigDecimal price() {         return new BigDecimal("3.0");     }     }  SandWichDecorator.java /**  * Base shape for Decorators, this shape inherit from Sandwich, thence that  * it tin give notice survive of same type, which is required to overstep decorators where  * original object is expected. Later, this shape volition likewise come upwards handy  * to render mutual functionalities to Decorators.  *  * @author  */ public abstract class SandWichDecorator extends Sandwich {           @Override     public abstract BigDecimal price();     }  CheeseDecorator.java import java.math.BigDecimal;  /**  * Influenza A virus subtype H5N1 Decorator class, which adds cheese (new functionality) into Sandwich object.  * This Decorator shape modifies price() in addition to getDescritption() method to implement  * novel behaviour.  *  * @author  */ public class CheeseDecorator extends SandWichDecorator{     Sandwich currentSandwich;         public CheeseDecorator(Sandwich sw){         currentSandwich = sw;     }         @Override     public String getDescription(){         return currentSandwich.getDescription() + ", Cheese";     }     @Override     public BigDecimal price() {         return currentSandwich.price().add(new BigDecimal("0.50"));     }     }   SandwichMaker.java /**  * Test shape to demonstrate How Decorator Pattern inward Java piece of work together. This class  * get-go creates a Sandwich in addition to decorates it amongst extra cheese. This is dainty example  * of how to render novel functionalities to an object at runtime using Decorator Pattern.  *  * @author Javain Paul  */ public class SandwichMaker {         public static void main(String args[]){                 Sandwich mySandwich = new WhiteBreadSandWich("White breadstuff Sandwich");         System.out.printf("Price of %s is $%.2f %n", mySandwich.getDescription(), 
                                                     mySandwich.price());                 //adding extra cheese using Decorator Pattter         mySandwich = new CheeseDecorator(mySandwich);         System.out.printf("Price of %s is $%.2f %n", mySandwich.getDescription(), 
                                                     mySandwich.price());     } }  Output: Price of White breadstuff Sandwich is $3.00 Price of White breadstuff Sandwich, Cheese is $3.50

You tin give notice meet that at i time cost is easily calculated based upon the toppings in addition to extras y'all add together on Sandwich. These blueprint patterns are rattling useful for writing code which tin give notice withstand the examine of fourth dimension in addition to that's why every serious programmer should larn patterns. If y'all desire to larn to a greater extent than virtually other OOP blueprint pattern similar Decorator thence y'all tin give notice bring a facial expression at the interface of the object or past times extending an abstract class of the original class.

2) The decorator pattern is based on Composition, which way it needs an original object to decorate it. This is achieved past times creating a constructor on decorator shape which accepts a base of operations type of original object. similar inward this illustration constructor of CheeseDecorator accepts Sandwich object. 

3) Decorator shape adds novel functionality earlier or later on delegating the chore to the original object. In this example, the cost of Decorator i.e. cheese is included later on calculating the cost of White Bread Sandwich.

4) The decorator pattern is likewise a practiced illustration of Open Closed blueprint principle, which is i of the cardinal principles from Uncle Bob's SOLID blueprint principles. If y'all desire to larn to a greater extent than virtually SOLID principles, delight depository fiscal establishment check the courses)
  • Difference betwixt Factory in addition to Dependency Injection Pattern? (answer)
  • How to create thread-safe Singleton inward Java? (example)
  • How to implement the Strategy Design Pattern inward Java? (example)
  • Difference betwixt Factory in addition to AbstractFactory Pattern? (example)
  • 18 Java Design Pattern Interview Questions amongst Answers (list)
  • Difference betwixt Factory in addition to Abstract Factory pattern inward Java (answer)
  • How to blueprint a Vending Machine inward Java? (questions)
  • 20 System Design Interview Questions (list)
  • How to acquire a method of HashMap plant internally inward Java? (answer)
    Difference betwixt Abstraction in addition to Encapsulation inward Java? (answer)
  • Difference betwixt State in addition to Strategy Design Pattern inward Java? (answer)
  • Top v Courses to larn Design Patterns inward Java (courses)
  • 5 Free Courses to larn Data Structure in addition to Algorithms (courses)
  • Thanks a lot for reading this article thence far. If y'all similar this Decorator blueprint pattern tutorial inward Java thence delight percentage amongst your friends in addition to colleagues. If y'all receive got whatsoever questions or feedback thence delight drib a note.

    P. S. - If y'all desire to larn to a greater extent than virtually blueprint patterns in addition to how they tin give notice assistance y'all to write meliorate code inward Java, I advise y'all bring a facial expression at the Java Design Patterns in addition to Architecture - a Free course of written report on Udemy.

    No comments:

    Post a Comment