Tuesday, 29 October 2013

Adapter Design pattern - keypoints

🚀 Enjoying Java Tutorials?

Subscribe to Ram N Java for clean, beginner-friendly core Java tutorials and interview prep!

🔔 Subscribe to Ram N Java

Introduction

The Adapter Design Pattern is one of the most frequently asked structural design patterns in technical interviews. It allows two incompatible interfaces to collaborate seamlessly without modifying existing source code. Below is a curated, comprehensive summary of the essential concepts, implementation variations, and interview takeaways you need to know.

1. Intent & Core Purpose

  • Structural Pattern: Adapter is categorized under Gang of Four (GoF) structural design patterns because it concerns class and object composition.
  • Bridge Incompatibility: It converts the interface of a class into another interface that clients expect, letting classes work together that couldn't otherwise due to incompatible interfaces.
  • Also Known As: Wrapper Pattern, because the adapter wraps the existing class (adaptee) inside a compatible layer.

2. The 4 Essential Participants

Participant Role in Architecture
Client Contains the business logic and interacts only via the Target interface.
Target Interface Defines the domain-specific contract and methods that the Client expects to invoke.
Adaptee Existing class or third-party library offering the required functionality under an incompatible interface.
Adapter The intermediate class that implements Target and translates requests to Adaptee method calls.

3. Object Adapter vs. Class Adapter

  • Object Adapter (Composition):
    • Uses object composition by maintaining an instance variable reference to the Adaptee.
    • Implements the Target interface and delegates calls to the composed Adaptee instance.
    • Advantage: Can adapt an Adaptee and any of its subclasses simultaneously. Favors the OOP principle: favor composition over inheritance.
  • Class Adapter (Inheritance):
    • Uses multiple inheritance (in C++) or extends the Adaptee class while implementing the Target interface (in Java).
    • Directly calls inherited superclass methods without creating a separate instance.
    • Trade-off: Commits to a concrete Adaptee class, making it less flexible when working with Adaptee subclasses.

4. When Should You Use It?

  • When you want to reuse an existing class whose interface does not match the one you need.
  • When integrating third-party libraries, legacy components, or APIs whose source code cannot be modified.
  • When building reusable modules that need to coordinate with unrelated or unforeseen classes that don't share compatible interfaces.

5. Real Examples in Java Standard Library

  • java.util.Arrays#asList(): Adapts an array into a standard List interface.
  • java.io.InputStreamReader(InputStream): Adapts a byte stream (InputStream) into a character stream (Reader).
  • java.io.OutputStreamWriter(OutputStream): Adapts a byte stream (OutputStream) into a character stream (Writer).
  • java.util.Collections#enumeration() & list(): Adapts between legacy Enumeration and modern Iterator / Collection interfaces.

Related Tutorials from Ram N Java


Click here to watch in Youtube : https://www.youtube.com/watch?v=mGJRT0TWO5k

Click the below Image to Enlarge


Adapter Design pattern - Real Time Exmaple(Translator)

🚀 Enjoying Java Tutorials?

Subscribe to Ram N Java for clean, beginner-friendly core Java tutorials and interview prep!

🔔 Subscribe to Ram N Java

Introduction

The Adapter Design Pattern is a structural design pattern that allows two incompatible interfaces to communicate seamlessly without modifying their existing behavior. A clear and intuitive real-life analogy to understand this concept is human language translation: communication between two people who speak entirely different languages.

The Communication Problem

Consider two individuals trying to hold a conversation:

  • David (from USA): Speaks and understands only English. He does not know French.
  • Rohit (from France): Speaks and understands only French. He does not know English.

If David wants to communicate with Rohit, or Rohit wants to communicate with David, direct communication is impossible because neither speaks the other's language. Their communication interfaces are incompatible.

The Solution: Introducing John as the Adapter

To resolve this issue, we introduce an intermediary person named John:

  • John knows both English and French fluently.
  • He can listen in English and speak in French, as well as listen in French and speak in English.
  • John acts as the Adapter / Translator bridging David and Rohit.

How the Flow Works

  1. David says "How are you?" in English to John.
  2. John translates "How are you?" into French ("Comment allez-vous?") and passes it to Rohit.
  3. Rohit receives the French message and replies in French ("Très bien, merci") to John.
  4. John translates the French reply back into English ("I am fine, thank you") and speaks it to David.

Through John, David and Rohit converse effectively without either of them having to learn a new language. This is precisely how the Adapter Pattern works in software architecture.

Adapter Pattern Role Mapping

Pattern Role Real-World Participant Role Description
Client David Initiator who understands only English
Target Interface English Interface The language/protocol David expects to interact with
Adaptee Rohit Target receiver who understands only French
Adapter John Translates and converts requests and responses between both parties

Related Tutorials from Ram N Java


Click here to watch in Youtube : https://www.youtube.com/watch?v=hCkFDDPdO-8

Click the below Image to Enlarge

Adapter Design pattern - Real Time Exmaple(Translator)
















See also:

  • Adapter Design pattern - Introduction
  • Adapter Design pattern - Real Time Example (Card Reader)
  • Adapter Design pattern - Real Time Example (Mobile Charger)
  • Adapter Design pattern - Real Time Example (Universal Adaptor)
  • Adapter Design pattern - Real Time Example [JDBC Driver]
  • Adapter Design pattern - Class diagram
  • Adapter Design Pattern - Sequence diagram
  • Adapter Design Pattern - Implementation [Language Translator]
  • Adapter Pattern - Implementation [Object Adapter]
  • Adapter Pattern - Implementation [Class Adapter]
  • Adapter Design Pattern - Implementation [Mobile Charger]
  • Adapter Design Pattern - Key Points
  • All Design Patterns Links
  • Thursday, 17 October 2013

    Prototype Design pattern - Implementation

    🚀 Enjoying Java Design Patterns?

    Subscribe to Ram N Java for clean, step-by-step programming guides and architecture insights!

    🔔 Subscribe to Ram N Java

    What Is the Prototype Design Pattern?

    The Prototype Design Pattern is a creational pattern used when object creation is expensive or time-consuming. Instead of building brand-new objects from scratch using the new keyword, this pattern clones an existing prototype object and modifies only the properties that need changing.

    The Problem: Costly Object Construction

    Imagine constructing a complex Dog object composed of several smaller sub-objects (e.g., DogLeg, DogEar, DogEye, and DogTail), along with attributes like name, age, and color:

    • Building each sub-object repeatedly creates noticeable overhead.
    • If you need hundreds of similar dog objects with slight variations (such as changing the color from white to brown), executing full construction every time degrades performance.

    The Solution: Clone and Customize

    With the Prototype pattern, the object is instantiated completely only once:

    1. Initial Build: The prototype object is created using new and stored in an object registry (such as a Map or Cache).
    2. Cloning: When a new instance is needed, the registry clones the cached prototype via a clone() method.
    3. Customization: The caller modifies only the specific attributes (like name, age, or color) without re-instantiating all the underlying sub-objects.

    Core Components in Java

    • Cloneable Interface: Defines an abstract clone() contract implemented by target domain classes.
    • Concrete Prototype: Implements the cloning logic to return a reliable copy.
    • Prototype Registry (AnimalHash): Maintains initialized prototype instances inside a key-value store to deliver instant clones to clients on demand.

    Recommended Next Videos

    Continue mastering design patterns with these related tutorials from our channel:


    Click here to watch in Youtube : https://www.youtube.com/watch?v=nZqoK4uaoZc

    Click the below Image to Enlarge
    Prototype Design pattern - Implementation
    Prototype Design pattern - Implementation - Class Diagram









































    Dogear.java

    public class Dogear
    {
    private int numberOfEars;

    public int getNumberOfEars()
    {
    return numberOfEars;
    }

    public void setNumberOfEars( int numberOfEars )
    {
    this.numberOfEars = numberOfEars;
    }

    @Override
            public String toString()
            {
           return "Dogear [numberOfEars=" + numberOfEars + "]";
            }


    }

    Dogeye.java

    public class Dogeye
    {
    private int numberOfEyes;

    public int getNumberOfEyes()
    {
    return numberOfEyes;
    }

    public void setNumberOfEyes( int numberOfEyes )
    {
    this.numberOfEyes = numberOfEyes;
    }

    @Override
            public String toString()
            {
           return "Dogeye [numberOfEyes=" + numberOfEyes + "]";
            }


    }


    Dogleg.java

    public class Dogleg
    {
    private int numberOflegs;

    public int getNumberOflegs()
    {
    return numberOflegs;
    }

    public void setNumberOflegs( int numberOflegs )
    {
    this.numberOflegs = numberOflegs;
    }

    @Override
            public String toString()
            {
           return "Dogleg [numberOflegs=" + numberOflegs + "]";
            }


    }


    Dogtail.java

    public class Dogtail
    {
    private String tailLength; // long or small

    public String getTailLength()
    {
    return tailLength;
    }

    public void setTailLength( String tailLength )
    {
    this.tailLength = tailLength;
    }

    @Override
            public String toString()
            {
           return "Dogtail [tailLength=" + tailLength + "]";
            }

    }


    Animal.java

    public interface Animal extends Cloneable
    {
     public Animal clone();

    }


    Dog.java

    public class Dog implements Animal
    {

    private String  name;
    private int     age;
    private String  color;
    private Dogleg  dogleg;
    private Dogtail dogtail;
    private Dogear  dogear;
    private Dogeye  dogeye;

    public Dog( String name, int age, String color, Dogleg dogleg, Dogtail dogtail, Dogear dogear, Dogeye dogeye )
    {
    super();
    this.name = name;
    this.age = age;
    this.color = color;
    this.dogleg = dogleg;
    this.dogtail = dogtail;
    this.dogear = dogear;
    this.dogeye = dogeye;
    }

    public Dogleg getDogleg()
    {
    return dogleg;
    }

    public void setDogleg( Dogleg dogleg )
    {
    this.dogleg = dogleg;
    }

    public Dogtail getDogtail()
    {
    return dogtail;
    }

    public void setDogtail( Dogtail dogtail )
    {
    this.dogtail = dogtail;
    }

    public Dogear getDogear()
    {
    return dogear;
    }

    public void setDogear( Dogear dogear )
    {
    this.dogear = dogear;
    }

    public Dogeye getDogeye()
    {
    return dogeye;
    }

    public void setDogeye( Dogeye dogeye )
    {
    this.dogeye = dogeye;
    }

    public String getName()
    {
    return name;
    }

    public void setName( String name )
    {
    this.name = name;
    }

    public int getAge()
    {
    return age;
    }

    public void setAge( int age )
    {
    this.age = age;
    }

    public String getColor()
    {
    return color;
    }

    public void setColor( String color )
    {
    this.color = color;
    }

    public Animal clone()
    {

    Dog dogObject = null;

    try
    {

    dogObject = (Dog) super.clone();

    }

    catch( CloneNotSupportedException e )
    {

    e.printStackTrace();

    }

    return dogObject;
    }

    @Override
    public String toString()
    {
    return "Dog [name=" + name + ", age=" + age + ", color=" + color + ", dogleg=" + dogleg + ", dogtail="
                   + dogtail + ", dogear=" + dogear + ", dogeye=" + dogeye + "]";
    }

    }


    AnimalCache.java

    import java.util.Hashtable;

    public class AnimalCache
    {
    private static Hashtable<String, Animal> AnimalMap = new Hashtable<String, Animal>();

    public static Animal getAnimal( String animalType )
    {
    Dog dog = (Dog) AnimalMap.get(animalType);
    if( dog == null )
    {
    Dogleg dogleg = new Dogleg();
    dogleg.setNumberOflegs(4);

    Dogear dogear = new Dogear();
    dogear.setNumberOfEars(2);

    Dogtail dogtail = new Dogtail();
    dogtail.setTailLength("long");

    Dogeye dogeye = new Dogeye();
    dogeye.setNumberOfEyes(2);

    dog = new Dog("Tommy", 3, "White", dogleg, dogtail, dogear, dogeye);
    AnimalMap.put("dog", dog);
    System.out.println("New Dog Object is created and return\n");
    return dog;
    }
    System.out.println("\nCloned Dog Object is created and return\n");
    return dog.clone();
    }
    }


    PrototypePatternDemo.java

    public class PrototypePatternDemo
    {

    public static void main(String[] args)
    {

    Dog dog = (Dog) AnimalCache.getAnimal("dog");
    displayAnimalProperty(dog);

    Dog cloneddog1 = (Dog) AnimalCache.getAnimal("dog");
    cloneddog1.setName("Jonnie");
    cloneddog1.setAge(4);
    cloneddog1.setColor("Brown");
    displayAnimalProperty(cloneddog1);

    Dog cloneddog2 = (Dog) AnimalCache.getAnimal("dog");
    cloneddog2.setName("Tony");
    cloneddog2.setAge(5);
    cloneddog2.setColor("Brown");
    displayAnimalProperty(cloneddog2);

    Dog cloneddog3 = (Dog) AnimalCache.getAnimal("dog");
    cloneddog3.setName("Jimmy");
    cloneddog3.setAge(8);
    cloneddog3.setColor("Brown");
    displayAnimalProperty(cloneddog3);

    }

    public static void displayAnimalProperty(Animal animal)
    {
    if (animal instanceof Dog)
    {
    Dog dog = (Dog) animal;
    System.out.println(dog.toString());
    System.out.println("-----------------------------------------------------------------------------------------------------");

    }
    }

    }

    Output

    New Dog Object is created and return

    Dog [name=Tommy, age=3, color=White, dogleg=Dogleg [numberOflegs=4], dogtail=Dogtail [tailLength=long], dogear=Dogear [numberOfEars=2], dogeye=Dogeye [numberOfEyes=2]]
    -----------------------------------------------------------------------------------------------------

    Cloned Dog Object is created and return

    Dog [name=Jonnie, age=4, color=Brown, dogleg=Dogleg [numberOflegs=4], dogtail=Dogtail [tailLength=long], dogear=Dogear [numberOfEars=2], dogeye=Dogeye [numberOfEyes=2]]
    -----------------------------------------------------------------------------------------------------

    Cloned Dog Object is created and return

    Dog [name=Tony, age=5, color=Brown, dogleg=Dogleg [numberOflegs=4], dogtail=Dogtail [tailLength=long], dogear=Dogear [numberOfEars=2], dogeye=Dogeye [numberOfEyes=2]]
    -----------------------------------------------------------------------------------------------------

    Cloned Dog Object is created and return

    Dog [name=Jimmy, age=8, color=Brown, dogleg=Dogleg [numberOflegs=4], dogtail=Dogtail [tailLength=long], dogear=Dogear [numberOfEars=2], dogeye=Dogeye [numberOfEyes=2]]
    -----------------------------------------------------------------------------------------------------


    See also:


  • Prototype Design Pattern - Introduction
  • Prototype Design Pattern - Class Diagram
  • Prototype Design Pattern - KeyPoints
  • All Design Patterns Links
  • Prototype Design pattern - keyPoints

    🚀 Level Up Your Java Skills!

    Subscribe to Ram N Java for concise design pattern summaries, architecture best practices, and code examples!

    🔔 Subscribe to Ram N Java

    Summary & Core Concepts

    The Prototype Design Pattern is a foundational creational pattern in object-oriented programming. Its primary goal is to produce new objects by cloning a pre-existing archetype rather than invoking heavy constructor logic. Reviewing these key takeaways will help you identify exactly when and how to implement it effectively.

    Key Takeaways and Best Practices

    • Minimizes Expensive Overhead: Ideal for objects that require heavy database operations, file I/O, or complex initialization logic. Cloning an existing object is significantly faster.
    • Decouples Concrete Classes: Client code interacts with an abstract prototype or interface, allowing you to add or remove concrete prototypes without modifying client business logic.
    • Shallow vs. Deep Copy: Always evaluate your object graph. A shallow copy duplicates primitive fields but shares object references, whereas a deep copy creates distinct clones of nested objects to prevent shared state issues.
    • Registry Pattern Integration: Prototypes are often managed via a prototype manager or cache (such as a Map), giving clients an easy lookup mechanism to retrieve new cloned instances by key.

    Recommended Learning Path

    To gain a complete, 360-degree understanding of this creational pattern, explore the topic in this order:

    1. Introduction & Fundamentals: Understand the real-world motivations and core principles.
    2. Class Diagram & Architecture: Examine how Prototype, ConcretePrototype, and Client components connect.
    3. Implementation & Code: Write and test working Java examples using object cloning and registries.
    4. Key Insights & Review: Solidify your understanding with quick revision points and architectural trade-offs.

    Recommended Next Videos

    Expand your software design skills with these design pattern tutorials from our channel:


    Click here to watch in Youtube : https://www.youtube.com/watch?v=R0f83lh9Tz0

    Click the below Image to Enlarge
























    See also:

  • Prototype Design Pattern - Introduction
  • Prototype Design Pattern - Class Diagram
  • Prototype Design Pattern - Implementation
  • All Design Patterns Links
  • Prototype Design pattern - Class Diagram

    🚀 Master Object-Oriented Design!

    Subscribe to Ram N Java for intuitive UML diagrams, architecture walkthroughs, and practical coding tutorials!

    🔔 Subscribe to Ram N Java

    Deconstructing the Prototype Class Diagram

    To successfully implement the Prototype Design Pattern in software development, understanding its UML structure is critical. The class diagram visualizes how the client, prototype contracts, and concrete implementations collaborate to duplicate objects smoothly without tightly coupling client code to specific classes.

    Key Components and Participants

    • Client: The class that initiates object creation. Instead of calling a constructor directly, it requests a new instance via the cloning interface.
    • Prototype (Interface / Abstract Class): Declares the abstract cloning method (typically clone()) that all cloneable types must provide.
    • Concrete Prototype: Implements the cloning operation to return a precise copy of itself, handling primitive data copying and reference management.
    • Prototype Manager / Registry (Optional): A repository or cache (such as a HashMap) that keeps key-value pairs of initialized prototypes for quick lookup and on-demand cloning.

    How the Flow Works

    1. Preloading: During startup, prototype objects are initialized once and saved in the registry with unique identifiers.
    2. Request: The client asks the registry or prototype for a copy using a key identifier.
    3. Duplication: The concrete prototype executes its clone() method, creating a duplicate instance.
    4. Modification: The client receives the duplicate object and updates fields as needed, leaving the original prototype intact.

    Architectural Advantages

    • Encapsulates Instantiation Complexity: Hides complex object creation pipelines from consumer classes.
    • Runtime Flexibility: New concrete prototype variants can be added or registered at runtime without altering the client implementation.
    • Cleaner Inheritance Trees: Avoids building parallel class hierarchies of factories merely to instantiate specific classes.

    Recommended Next Videos

    Deepen your software engineering knowledge with these related design pattern tutorials from our channel:


    Click here to watch in Youtube : https://www.youtube.com/watch?v=333z-1k14KE

    Click the below Image to Enlarge
    Prototype Design pattern - Class Diagram
























    See also:

  • Prototype Design Pattern - Introduction
  • Prototype Design Pattern - Implementation
  • Prototype Design Pattern - KeyPoints
  • All Design Patterns Links
  • Prototype Design Pattern - Introduction

    🚀 Master Java Architecture & Design Patterns!

    Subscribe to Ram N Java for beginner-friendly coding tutorials, real-world design patterns, and programming tips!

    🔔 Subscribe to Ram N Java

    Introduction to the Prototype Design Pattern

    In software engineering, creating new objects using standard constructors and the new keyword can sometimes be an expensive, resource-heavy operation. The Prototype Design Pattern is a classic creational design pattern that solves this problem by allowing you to duplicate or clone existing objects without coupling your code to their specific classes.

    Why Use the Prototype Pattern?

    When an object requires intensive computations, file reads, or complex database lookups during initialization, instantiating it repeatedly causes noticeable performance degradation. Instead of starting from scratch every single time:

    • You build and configure an original benchmark instance (the prototype).
    • Whenever another similar instance is needed, you simply create a copy (a clone).
    • You update only the specific fields that need differentiation, saving processing time and system memory.

    A Simple Real-World Analogy

    Think of an architectural blueprint or a rubber stamp. Instead of drawing a detailed schematic by hand every time you need a document, you create a master template once. You duplicate that master template and fill in only the unique customer details on each copy. In software, the Prototype pattern performs the exact same role for complex objects.

    Core Fundamentals to Remember

    • Creational Category: Focuses specifically on object creation mechanisms and instantiations.
    • Cloning Contract: Classes declare a cloning interface (like clone() in Java) so clients can trigger duplication uniformly.
    • Decoupled Instantiation: The client program does not need to know the intricate setup steps or internal attributes of the concrete object being duplicated.

    Recommended Next Videos

    Expand your software design foundation with these related tutorials from our channel:


    Click here to watch in Youtube : https://www.youtube.com/watch?v=3-ycjbJkqv4

    Click the below Image to Enlarge
    Prototype Design Pattern - Introduction
























    See also:

  • Prototype Design Pattern - Class Diagram
  • Prototype Design Pattern - Implementation
  • Prototype Design Pattern - KeyPoints
  • All Design Patterns Links
  • Tuesday, 15 October 2013

    Chain of Responsibility Design pattern - Implementation(One or more Rece...

    🚀 Master Java Design Patterns & Software Architecture!

    Subscribe to Ram N Java for clean software architecture patterns, design pattern deep dives, and production-ready implementation guides!

    🔔 Subscribe to Ram N Java

    Understanding Multiple Receivers in Chain of Responsibility

    The Chain of Responsibility is a powerful behavioral design pattern that decouples the sender of a request from its potential receivers by passing the request along a chain of handlers. While the classic variant often halts as soon as a single receiver handles the request, many modern architectural scenarios—such as logging pipelines, security filters, event dispatchers, and data enrichment workflows—require multiple receivers to inspect, process, and pass the request forward along the entire chain.

    How Multiple Receiver Handling Works

    • Chained Handler Hierarchy: Each concrete handler maintains a reference to the next successor in the pipeline.
    • Non-Terminating Propagation: Instead of returning immediately after performing its operation, each handler executes its specific business logic and then explicitly delegates invocation to super.handleRequest() or nextHandler.handleRequest().
    • Incremental Request Enrichment: A single request object travels through each station in the sequence, allowing multiple handlers to validate, authenticate, transform, or log the payload sequentially.
    • Dynamic Pipeline Configuration: The sequence of handlers can be assembled or reordered dynamically at runtime without modifying client code or handler internals.

    Key Components in the Implementation

    1. Handler Interface/Abstract Class: Declares the contract for handling requests and stores the reference to the next successor.
    2. Concrete Handlers: Individual handler classes that inspect the request, apply their domain-specific logic, and forward the request downstream.
    3. Client: Configures the sequence of handlers and initiates the pipeline by sending a request to the first link in the chain.

    Architectural Advantages

    • Single Responsibility Principle (SRP): Isolates distinct processing concerns (such as validation, logging, and security) into separate, focused classes.
    • Open/Closed Principle (OCP): Allows adding, removing, or reordering processing steps without altering existing handler implementations.
    • Loose Coupling: The client remains completely agnostic of how many handlers process the request or their internal execution order.

    Recommended Next Videos

    Continue your deep dive into the Chain of Responsibility pattern with these related tutorials from our channel:


    Click here to watch in Youtube : https://www.youtube.com/watch?v=tyGnCb-kE1I

    Click the below Image to Enlarge
    Chain of Responsibility Design pattern - Implementation
    Chain of Responsibility Design pattern - Implementation - Class Diagram




































    RsHandler.java

    public abstract class RsHandler
    {
    RsHandler rsHandler;

    public void nextHandler( RsHandler rsHandler )
    {
    this.rsHandler = rsHandler;
    }

    public abstract void dispatchRs( long requestedAmount );

    }

    HundredRsHandler.java

    public class HundredRsHandler extends RsHandler
    {

    public void dispatchRs(long requestedAmount)
    {
    long numberofNotesToBeDispatched = requestedAmount / 100;
    if (numberofNotesToBeDispatched > 0)
    {
    if(numberofNotesToBeDispatched>1)
    {
    System.out.println(numberofNotesToBeDispatched + " ,Hundred Rs notes are dispatched by HundredRsHandler\n");
    }
    else
    {
    System.out.println(numberofNotesToBeDispatched + " ,Hundred Rs note is dispatched by HundredRsHandler\n");

    }
    }

    long pendingAmountToBeProcessed = requestedAmount % 100;

    if (pendingAmountToBeProcessed > 0)
    {
    rsHandler.dispatchRs(pendingAmountToBeProcessed);

    }

    }

    }

    FiftyRsHandler.java

    public class FiftyRsHandler extends RsHandler
    {
    public void dispatchRs(long requestedAmount)
    {
    long numberofNotesToBeDispatched = requestedAmount / 50;
    if (numberofNotesToBeDispatched > 0)
    {
    if (numberofNotesToBeDispatched > 1)
    {
    System.out.println(numberofNotesToBeDispatched + " ,Fifty Rs notes are dispatched by FiftyRsHandler\n");
    }
    else
    {
    System.out.println(numberofNotesToBeDispatched + " ,Fifty Rs note is dispatched by FiftyRsHandler\n");

    }

    }

    long pendingAmountToBeProcessed = requestedAmount % 50;

    if (pendingAmountToBeProcessed > 0)
    {
    rsHandler.dispatchRs(pendingAmountToBeProcessed);

    }

    }
    }


    TwentyRsHandler.java

    public class TwentyRsHandler extends RsHandler
    {
    public void dispatchRs(long requestedAmount)
    {
    long numberofNotesToBeDispatched = requestedAmount / 20;

    if (numberofNotesToBeDispatched > 0)
    {

    if (numberofNotesToBeDispatched > 1)
    {
    System.out.println(numberofNotesToBeDispatched + " ,Twenty Rs notes are dispatched by TwentyRsHandler\n");
    }
    else
    {
    System.out.println(numberofNotesToBeDispatched + " ,Twenty Rs note is dispatched by TwentyRsHandler\n");

    }
    }

    long pendingAmountToBeProcessed = requestedAmount % 20;

    if (pendingAmountToBeProcessed > 0)
    {
    rsHandler.dispatchRs(pendingAmountToBeProcessed);

    }

    }
    }


    FiveRsHandler.java

    public class FiveRsHandler extends RsHandler
    {
    public void dispatchRs(long requestedAmount)
    {
    long numberofNotesToBeDispatched = requestedAmount / 5;
    if (numberofNotesToBeDispatched > 0)
    {

    if (numberofNotesToBeDispatched > 1)
    {
    System.out.println(numberofNotesToBeDispatched + " ,Five Rs notes are dispatched by FiveRsHandler\n");
    }
    else
    {
    System.out.println(numberofNotesToBeDispatched + " ,Five Rs note is dispatched by FiveRsHandler\n");

    }
    }

    long pendingAmountToBeProcessed = requestedAmount % 5;

    if (pendingAmountToBeProcessed > 0)
    {
    rsHandler.dispatchRs(pendingAmountToBeProcessed);

    }

    }
    }


    ATM.java

    public class ATM
    {
    private static HundredRsHandler hundredRsHandler = new HundredRsHandler();
    private static FiftyRsHandler   fiftyRsHandler   = new FiftyRsHandler();
    private static TwentyRsHandler  twentyRsHandler  = new TwentyRsHandler();
    private static FiveRsHandler    fiveRsHandler    = new FiveRsHandler();

    static
    {
    // Prepare the chain of Handlers
    hundredRsHandler.nextHandler(fiftyRsHandler);
    fiftyRsHandler.nextHandler(twentyRsHandler);
    twentyRsHandler.nextHandler(fiveRsHandler);
    }

    public void withdraw( long requestedAmount )
    {

    hundredRsHandler.dispatchRs(requestedAmount);
    }
    }


    ChainOfResDemo.java

    public class ChainOfResDemo
    {

    public static void main( String[] args )
    {
    ATM atm = new ATM();
    System.out.println("\n ----------------Requested Amount 475-----------------------\n");
    atm.withdraw(475);
    System.out.println("\n ----------------Requested Amount 455-----------------------\n");
    atm.withdraw(455);
    System.out.println("\n ----------------Requested Amount 520-----------------------\n");
    atm.withdraw(520);
    }

    }


    Output

     ----------------Requested Amount 475-----------------------

    4 ,Hundred Rs notes are dispatched by HundredRsHandler

    1 ,Fifty Rs note is dispatched by FiftyRsHandler

    1 ,Twenty Rs note is dispatched by TwentyRsHandler

    1 ,Five Rs note is dispatched by FiveRsHandler


     ----------------Requested Amount 455-----------------------

    4 ,Hundred Rs notes are dispatched by HundredRsHandler

    1 ,Fifty Rs note is dispatched by FiftyRsHandler

    1 ,Five Rs note is dispatched by FiveRsHandler


     ----------------Requested Amount 520-----------------------

    5 ,Hundred Rs notes are dispatched by HundredRsHandler

    1 ,Twenty Rs note is dispatched by TwentyRsHandler



    Tutorials