Monday, 27 January 2014

State Design pattern - Real time example [Project]

Master Practical Java Architecture & Design Patterns!

Subscribe to Ram N Java for clean coding tutorials, GoF design patterns, and real-world system implementations!

🔔 Subscribe to Ram N Java

The Lifecycle Problem in Project Management

In project management systems, software projects and enterprise tasks pass through multiple distinct lifecycle phases:

  • Initiated / Planning: Defining scope, assigning teams, and validating requirements before active development starts.
  • In Progress: Active implementation where tasks are executed, commits are tracked, and milestones are updated.
  • Testing / QA: Bug reporting, regression validation, and quality sign-offs before deployment.
  • Completed / Closed: Archived milestones where edits or task additions are restricted.

Managing these shifting requirements with traditional flag variables or nested if-else and switch-case blocks quickly produces brittle code that is vulnerable to bugs whenever a workflow rule changes or a new state is added.

Architecture of the State Pattern Solution

The State Design Pattern solves this complexity by turning each project lifecycle phase into a dedicated class and delegating behavior based on the current active state:

  • State Interface: Outlines allowed actions across project stages (e.g., assignTeam(), startDevelopment(), submitForQA(), closeProject()).
  • Concrete State Classes: Classes such as PlannedState, InProgressState, and CompletedState encapsulate stage-specific validations and trigger transitions to subsequent states.
  • Context Class (Project): Holds project metadata, maintains a reference to the active state instance, and delegates client requests to it dynamically at runtime.

Key Architectural Benefits

Applying the State pattern to project management workflows yields significant engineering benefits:

  • Elimination of Bulky Conditionals: Replaces messy state flags with clean, polymorphic method dispatching.
  • Single Responsibility Principle: Keeps state validation rules, business policies, and lifecycle transitions cleanly separated in their own classes.
  • Open/Closed Principle: Adding new project states (e.g., On-Hold, Cancelled, or Review) requires adding new classes without altering existing state logic.

Related Tutorials from Ram N Java


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

Click the below Image to Enlarge
State Design pattern - Real time example [Project]


















See also:

  • State Design pattern - Introduction
  • State Design pattern - Real time example [ATM]
  • State Design pattern - Real time example [TV Remote]
  • State Design pattern - Real time example [Vending Machine]
  • State Design pattern - Class Diagram
  • State Design pattern - Implementation [ATM]
  • State Design pattern - Implementation [Vending Machine]
  • State Design pattern - Implementation [Project]
  • State Design pattern - Implementation [LED TV]
  • State Design pattern - Keypoints
  • All Design Patterns Links
  • State Design pattern - Class Diagram

    Master UML Class Diagrams & Architecture!

    Subscribe to Ram N Java for clean class diagrams, design pattern tutorials, and real-world coding guides!

    🔔 Subscribe to Ram N Java

    Anatomy of the State Pattern Class Diagram

    The State Design Pattern allows an object to alter its behavior when its internal state changes, making it appear as if the object changed its class. In a UML class diagram, this pattern is structured around three key participants:

    • Context: Defines the client-facing interface. It maintains a reference to an instance of a State subclass that defines the current state, delegating all state-dependent requests to this object.
    • State Interface / Abstract Class: Declares an interface encapsulating the behavior associated with a particular state of the Context.
    • ConcreteState Subclasses: Each subclass implements behavior associated with a specific operational state of the Context (e.g., ConcreteStateA, ConcreteStateB) and can decide when and how to transition to other states.

    Relationships & Flow of Control

    The structural elegance of the State pattern lies in how Context and State collaborate:

    1. Aggregation / Composition: The Context maintains a reference to a State object (state: State).
    2. Delegation: When a client invokes a method on Context.request(), the Context forwards execution to state.handle().
    3. State Transitions: Concrete state objects or the Context update the active state reference by calling Context.setState(newState), seamlessly switching runtime behavior.

    Key Architectural Benefits

    Structuring your code around the State pattern class diagram brings major software engineering improvements:

    • Eliminates Conditional Complexity: Replaces massive, nested if-else or switch-case statements with clean polymorphism.
    • Single Responsibility Principle: Organizes state-specific behaviors into individual, isolated classes.
    • Open/Closed Principle: Adding new states simply involves introducing a new concrete state class without altering existing ones.

    Related Tutorials from Ram N Java


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

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


















    See also:

  • State Design pattern - Introduction
  • State Design pattern - Real time example [ATM]
  • State Design pattern - Real time example [TV Remote]
  • State Design pattern - Real time example [Vending Machine]
  • State Design pattern - Real time example [Project]
  • State Design pattern - Implementation [ATM]
  • State Design pattern - Implementation [Vending Machine]
  • State Design pattern - Implementation [Project]
  • State Design pattern - Implementation [LED TV]
  • State Design pattern - Keypoints
  • All Design Patterns Links
  • Sunday, 26 January 2014

    Bridge Design pattern - Implementation [LED TV]

    Master Software Architecture & Clean Code!

    Subscribe to Ram N Java for clean code, design pattern implementations, and practical Java tutorials!

    SUBSCRIBE NOW

    What is the Bridge Design Pattern?

    The Bridge Design Pattern is a structural pattern whose main goal is to decouple an abstraction from its implementation so that both can vary independently. Instead of relying heavily on inheritance—which often leads to an explosion of subclasses—the Bridge pattern prefers object composition.

    In this LED TV example, the user control interface (like a remote control) acts as the abstraction, while the actual TV hardware (Sony, Samsung, LG) acts as the implementation.

    Complete Java Code Implementation

    Below is a clean, practical implementation illustrating the Bridge pattern using an LED TV and remote control hierarchy:

    // 1. Implementor Interface
    interface LedTv {
        void on();
        void off();
        void switchChannel(int channel);
    }
    
    // 2. Concrete Implementors
    class SonyLedTv implements LedTv {
        @Override
        public void on() {
            System.out.println("Sony TV is turned ON.");
        }
        @Override
        public void off() {
            System.out.println("Sony TV is turned OFF.");
        }
        @Override
        public void switchChannel(int channel) {
            System.out.println("Sony TV tuned to channel: " + channel);
        }
    }
    
    class SamsungLedTv implements LedTv {
        @Override
        public void on() {
            System.out.println("Samsung TV is turned ON.");
        }
        @Override
        public void off() {
            System.out.println("Samsung TV is turned OFF.");
        }
        @Override
        public void switchChannel(int channel) {
            System.out.println("Samsung TV tuned to channel: " + channel);
        }
    }
    
    // 3. Abstraction (Bridge container)
    abstract class RemoteControl {
        protected LedTv tv;
    
        public RemoteControl(LedTv tv) {
            this.tv = tv;
        }
    
        public abstract void turnOn();
        public abstract void turnOff();
        public abstract void setChannel(int channel);
    }
    
    // 4. Refined Abstraction
    class BasicRemoteControl extends RemoteControl {
        public BasicRemoteControl(LedTv tv) {
            super(tv);
        }
    
        @Override
        public void turnOn() {
            tv.on();
        }
    
        @Override
        public void turnOff() {
            tv.off();
        }
    
        @Override
        public void setChannel(int channel) {
            tv.switchChannel(channel);
        }
    }
    
    // 5. Client Application
    public class BridgePatternDemo {
        public static void main(String[] args) {
            // Control Sony TV
            LedTv sonyTv = new SonyLedTv();
            RemoteControl sonyRemote = new BasicRemoteControl(sonyTv);
            sonyRemote.turnOn();
            sonyRemote.setChannel(5);
            sonyRemote.turnOff();
    
            System.out.println("--------------------");
    
            // Control Samsung TV using the same abstraction
            LedTv samsungTv = new SamsungLedTv();
            RemoteControl samsungRemote = new BasicRemoteControl(samsungTv);
            samsungRemote.turnOn();
            samsungRemote.setChannel(12);
            samsungRemote.turnOff();
        }
    }

    Key Architectural Advantages

    • Decoupled Hierarchies: Both abstraction (Remotes) and implementation (TV brands) can grow independently without cross-affecting code.
    • Eliminates Class Explosion: Avoids creating permutations like SonyBasicRemote, SamsungBasicRemote, SonySmartRemote, etc.
    • Runtime Flexibility: Concrete implementations can be swapped easily at runtime through constructor or setter injection.

    Watch More Related Design Pattern Tutorials


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

    Click the below Image to Enlarge

    Bridge Design pattern - Implementation [LED TV]



















    Bridge Design pattern - Implementation [LED TV] - Class Diagram




























    LEDTV.java

    public interface LEDTV
    {
    public void switchOn();

    public void switchOff();

    public void setChannel(int channelNumber);
    }


    SamsungLedTv.java

    public class SamsungLedTv implements LEDTV
    {

    @Override
    public void switchOn()
    {
    System.out.println("Turning ON.. Samsung TV.");
    }

    @Override
    public void switchOff()
    {
    System.out.println("Turning Off.. Samsung TV.");

    }

    @Override
    public void setChannel( int channelNumber )
    {
    System.out.println("Setting channel Number " + channelNumber + ".. on Samsung TV");

    }

    }


    SonyLedTv.java

    public class SonyLedTv implements LEDTV
    {

    @Override
    public void switchOn()
    {
    System.out.println("Turning ON.. Sony TV.");
    }

    @Override
    public void switchOff()
    {
    System.out.println("Turning Off.. Sony TV.");

    }

    @Override
    public void setChannel( int channelNumber )
    {
    System.out.println("Setting channel Number " + channelNumber + ".. on Sony TV");

    }

    }


    AbstractRemoteControl.java

    abstract class AbstractRemoteControl
    {

    protected LEDTV ledTv;

    protected AbstractRemoteControl( LEDTV ledTv )
    {
    this.ledTv = ledTv;
    }

    public abstract void switchOn();

    public abstract void switchOff();

    public abstract void setChannel( int channelNumber );

    }

    SamsungRemoteControl.java

    public class SamsungRemoteControl extends AbstractRemoteControl
    {

    public SamsungRemoteControl( LEDTV ledtv )
    {
    super(ledtv);
    }

    @Override
    public void switchOn()
    {
    ledTv.switchOn();
    }

    @Override
    public void switchOff()
    {
    ledTv.switchOff();

    }

    @Override
    public void setChannel( int channelNumber )
    {
    ledTv.setChannel(channelNumber);
    }

    }

    SonyRemoteControl.java

    public class SonyRemoteControl extends AbstractRemoteControl
    {
    public SonyRemoteControl( LEDTV ledtv )
    {
    super(ledtv);
    }

    @Override
    public void switchOn()
    {
    ledTv.switchOn();
    }

    @Override
    public void switchOff()
    {
    ledTv.switchOff();

    }

    @Override
    public void setChannel( int channelNumber )
    {
    ledTv.setChannel(channelNumber);
    }
    }

    Client.java

    public class Client
    {

    public static void main( String[] args )
    {

    SonyRemoteControl sonyRemoteControl = new SonyRemoteControl(new SonyLedTv());
    sonyRemoteControl.switchOn();
    sonyRemoteControl.switchOff();
    sonyRemoteControl.setChannel(20);
    System.out.println("**********************************************************************");
    SamsungRemoteControl samsungRemoteControl = new SamsungRemoteControl(new SamsungLedTv());
    samsungRemoteControl.switchOn();
    samsungRemoteControl.switchOff();
    samsungRemoteControl.setChannel(20);
    }
    }

    Output

    Turning ON.. Sony TV.
    Turning Off.. Sony TV.
    Setting channel Number 20.. on Sony TV
    **********************************************************************
    Turning ON.. Samsung TV.
    Turning Off.. Samsung TV.
    Setting channel Number 20.. on Samsung TV

    See also:

  • Bridge Design pattern - Introduction
  • Bridge Design pattern - Real time example [Send Message]
  • Bridge Design pattern - Real time example [Publish Message]
  • Bridge Design pattern - Real time example [Shape]
  • Bridge Design pattern - Real time example [TV]
  • Bridge Design pattern - Class Diagram
  • Bridge Design pattern - Implementation [Shape]
  • Bridge Design pattern - Implementation [Send Message]
  • Bridge Design pattern - Implementation [Publish Message]
  • Bridge Design pattern - Keypoints
  • All Design Patterns Links
  • Bridge Design pattern - Implementation [Publish Message]

    Master Software Architecture & Clean Code!

    Subscribe to Ram N Java for clean code, design pattern implementations, and practical Java tutorials!

    SUBSCRIBE NOW

    What is the Bridge Design Pattern?

    The Bridge Design Pattern decouples an abstraction from its implementation so that both can evolve independently. Instead of relying on rigid, multi-level class inheritance—which causes an explosion of subclasses—the Bridge pattern connects separate class hierarchies through composition.

    In a message publishing or notification system, the type of message being processed (e.g., text, encrypted, or urgent) acts as the abstraction, while the delivery platform (e.g., Email, SMS, or Push Notification) serves as the concrete implementation.

    Complete Java Code Implementation

    Below is a clean, practical Java implementation illustrating the Bridge pattern with a real-world message publishing architecture:

    // 1. Implementor Interface
    interface MessageSender {
        void sendMessage(String message);
    }
    
    // 2. Concrete Implementors
    class EmailSender implements MessageSender {
        @Override
        public void sendMessage(String message) {
            System.out.println("Email: Sending message -> " + message);
        }
    }
    
    class SmsSender implements MessageSender {
        @Override
        public void sendMessage(String message) {
            System.out.println("SMS: Sending text -> " + message);
        }
    }
    
    // 3. Abstraction (Bridge holding the Implementor reference)
    abstract class Message {
        protected MessageSender messageSender;
    
        public Message(MessageSender messageSender) {
            this.messageSender = messageSender;
        }
    
        public abstract void publish(String content);
    }
    
    // 4. Refined Abstractions
    class TextMessage extends Message {
        public TextMessage(MessageSender messageSender) {
            super(messageSender);
        }
    
        @Override
        public void publish(String content) {
            messageSender.sendMessage("[Standard Text] " + content);
        }
    }
    
    class EncryptedMessage extends Message {
        public EncryptedMessage(MessageSender messageSender) {
            super(messageSender);
        }
    
        @Override
        public void publish(String content) {
            String encryptedContent = new StringBuilder(content).reverse().toString();
            messageSender.sendMessage("[Encrypted] " + encryptedContent);
        }
    }
    
    // 5. Client Application
    public class BridgePatternDemo {
        public static void main(String[] args) {
            // Send a text message via Email
            Message emailMessage = new TextMessage(new EmailSender());
            emailMessage.publish("Welcome to Ram N Java!");
    
            // Send an encrypted message via SMS
            Message smsMessage = new EncryptedMessage(new SmsSender());
            smsMessage.publish("TopSecretCode123");
    
            // Swap channels dynamically: Send encrypted content via Email
            Message secureEmail = new EncryptedMessage(new EmailSender());
            secureEmail.publish("ConfidentialReport2026");
        }
    }

    Key Architectural Advantages

    • Prevents Combinatorial Subclass Explosion: Adding 3 message types and 3 delivery channels creates only 6 classes instead of 9 tightly coupled variants.
    • Runtime Channel Switching: Delivery mechanisms can be injected dynamically at runtime based on configuration or user preferences.
    • Open/Closed Principle: You can add a new messaging format or a new transport channel without modifying existing classes.

    Watch More Related Design Pattern Tutorials


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

    Click the below Image to Enlarge

    Bridge Design pattern - Implementation [Publish Message]

    Bridge Design pattern - Implementation [Publish Message] - Class Diagram


    MessagePublisher.java

    public interface MessagePublisher
    {
    public void publishMessage(String message);
    }


    Facebook.java

    public class Facebook implements MessagePublisher
    {

    public void publishMessage(String message)
    {
    System.out.println("'"+message+ "' : This message has been published to public in Facebook Social networking site");
    }
    }

    Twitter.java

    public class Twitter implements MessagePublisher
    {

    public void publishMessage(String message)
    {
    System.out.println("'"+message+ "' : This message has been published to public in Twitter Social networking site");
    }
    }

    GooglePlus.java

    public class GooglePlus implements MessagePublisher
    {

    public void publishMessage(String message)
    {
    System.out.println("'"+message+ "' : This message has been published to public in GooglePlus Social networking site");
    }
    }


    Message.java

    abstract class Message
    {

    protected MessagePublisher messagePublisher;

    protected MessagePublisher getMessagePublisher()
    {
    return messagePublisher;
    }

    protected void setMessagePublisher( MessagePublisher messagePublisher )
    {
    this.messagePublisher = messagePublisher;
    }

    abstract public void publishMessage(String message);

    }

    LongMessage.java

    public class LongMessage extends Message
    {

    @Override
    public void publishMessage( String message )
    {
    messagePublisher.publishMessage(message);
    }

    }

    ShortMessage.java

    public class ShortMessage extends Message
    {

    private static int MESSAGE_LENGTH = 200;

    @Override
    public void publishMessage( String message )
    {
    if( message.length() <= MESSAGE_LENGTH )
    {
    messagePublisher.publishMessage(message);
    }
    else
    {
    System.out.println("Sorry message length is more cann't publish.....");
    }

    }

    }


    Client.java

    import java.util.Scanner;

    public class Client
    {

    public static void main( String[] args )
    {

    System.out.println("Please enter the Social networking site you want to use to publish the message  : 'Twitter' or 'Facebook' or 'GooglePlus'");
    Scanner scanner = new Scanner(System.in);
    String socialNetworkingSite = scanner.next();
    System.out.println("Please enter the message you want to publish");
    Scanner scanner1 = new Scanner(System.in);
    String message = scanner1.nextLine();

    if( "Twitter".equalsIgnoreCase(socialNetworkingSite) )
    {
    ShortMessage shortMessage = new ShortMessage();
    shortMessage.setMessagePublisher(new Twitter());
    shortMessage.publishMessage(message);
    }
    else if( "Facebook".equalsIgnoreCase(socialNetworkingSite) )
    {
    LongMessage longMessage = new LongMessage();
    longMessage.setMessagePublisher(new Facebook());
    longMessage.publishMessage(message);
    }
    else if( "GooglePlus".equalsIgnoreCase(socialNetworkingSite) )
    {
    LongMessage longMessage = new LongMessage();
    longMessage.setMessagePublisher(new GooglePlus());
    longMessage.publishMessage(message);
    }

    }
    }


    Output

    Please enter the Social networking site you want to use to publish the message  : 'Twitter' or 'Facebook' or 'GooglePlus'
    Twitter
    Please enter the message you want to publish
    hello
    'hello' : This message has been published to public in Twitter Social networking site


    Please enter the Social networking site you want to use to publish the message  : 'Twitter' or 'Facebook' or 'GooglePlus'
    Facebook
    Please enter the message you want to publish
    hello bow are you?
    'hello bow are you?' : This message has been published to public in Facebook Social networking site

    See also:

  • Bridge Design pattern - Introduction
  • Bridge Design pattern - Real time example [Send Message]
  • Bridge Design pattern - Real time example [Publish Message]
  • Bridge Design pattern - Real time example [Shape]
  • Bridge Design pattern - Real time example [TV]
  • Bridge Design pattern - Class Diagram
  • Bridge Design pattern - Implementation [Shape]
  • Bridge Design pattern - Implementation [Send Message]
  • Bridge Design pattern - Implementation [LED TV]
  • Bridge Design pattern - Keypoints
  • All Design Patterns Links
  • Saturday, 25 January 2014

    State Design pattern - Real time example [Vending Machine]

    Master Practical Java Architecture & Design Patterns!

    Subscribe to Ram N Java for clean coding tutorials, GoF design patterns, and real-world system implementations!

    🔔 Subscribe to Ram N Java

    The Real-Time Vending Machine Problem

    A classic, intuitive way to understand behavioral design patterns is by examining how everyday machines operate. Consider a Vending Machine: depending on what state the machine is currently in, pressing the exact same button produces completely different outcomes:

    • No Coin State: Pressing an item button does nothing, alerting the user to insert money first.
    • Has Coin State: The machine accepts item selections and prepares to dispense goods.
    • Dispensing State: User inputs are temporarily locked while the mechanism delivers the item.
    • Sold Out State: All purchase requests are rejected, preventing coin acceptance or prompting maintenance.

    If you manage these conditions using procedural flags and nested if-else or switch blocks, adding a new action or state turns the code into an unmaintainable maze of conditional logic.

    How the State Pattern Models the Machine

    The State Design Pattern solves this complexity by turning every operational condition into an independent class:

    • State Interface: Declares actions supported across various states—such as insertCoin(), ejectCoin(), selectItem(), and dispense().
    • Concrete State Classes: Classes like NoCoinState, HasCoinState, and SoldOutState define what happens when each action is invoked, preventing invalid transitions and transitioning the context to the next valid state.
    • Context (Vending Machine): Maintains the active state reference, delegating all incoming user actions directly to the current state object.

    Key Architectural Benefits

    Structuring state-driven systems with the State pattern delivers immediate engineering benefits:

    • Eliminates Massive Conditionals: Replaces fragile if-else trees with clean polymorphic method calls.
    • Single Responsibility Principle: Keeps state validation, transitions, and business rules cleanly isolated in their own classes.
    • Open/Closed Principle: Adding new states (like CardPaymentState or MaintenanceState) requires no modifications to existing state classes.

    Related Tutorials from Ram N Java


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

    Click the below Image to Enlarge

    State Design pattern - Real time example [Vending Machine]

















    See also:

  • State Design pattern - Introduction
  • State Design pattern - Real time example [ATM]
  • State Design pattern - Real time example [TV Remote]
  • State Design pattern - Real time example [Project]
  • State Design pattern - Class Diagram
  • State Design pattern - Implementation [ATM]
  • State Design pattern - Implementation [Vending Machine]
  • State Design pattern - Implementation [Project]
  • State Design pattern - Implementation [LED TV]
  • State Design pattern - Keypoints
  • All Design Patterns Links
  • State Design pattern - Real time example [TV Remote]

    Master Practical Java Architecture & Design Patterns!

    Subscribe to Ram N Java for clean coding tutorials, GoF design patterns, and real-world system implementations!

    🔔 Subscribe to Ram N Java

    The Real-Time TV Remote Problem

    Consider an everyday device we all use: a TV Remote Controller. The remote has buttons such as power, volume up, volume down, and channel change. However, how the remote responds to pressing a button depends entirely on the current operating state of the television:

    • If the TV is Off, pressing the power button turns it On, while volume and channel buttons have no effect.
    • If the TV is On, pressing the power button turns it Off and places it into standby mode, while volume and channel buttons adjust audio and change broadcasts.

    In traditional procedural code, you would implement this using conditional flags and nested if-else or switch-case statements. As more states are added—such as Mute, Input/Source Selection, or Menu Navigation—the conditional logic quickly becomes bloated, fragile, and hard to maintain.

    How the State Pattern Solves the TV Remote Scenario

    The State Design Pattern tackles this challenge by encapsulating state-specific behavior into dedicated classes, allowing the remote context to alter its behavior dynamically at runtime:

    • State Interface: Outlines operations common to states, such as doAction(TVContext context) or button presses.
    • Concrete State Classes: Classes like TVStartState and TVStopState define the behavior valid for that specific state and transition the TV to the next state when actions occur.
    • Context (TV Remote / Context): Maintains a reference to the active state instance and delegates button actions directly to that state object, keeping the client code clean and completely unaware of internal state checks.

    Key Architectural Benefits

    Applying the State pattern to this real-world scenario offers significant software engineering advantages:

    • Eliminates Bulky Conditionals: Replaces messy if-else blocks with clean, polymorphic method calls.
    • Single Responsibility Principle: Keeps the code related to each individual TV state isolated in its own dedicated class.
    • Open/Closed Principle: Adding new states (e.g., MuteState, GamingModeState) requires adding new classes without modifying existing state handlers.

    Related Tutorials from Ram N Java


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

    Click the below Image to Enlarge
    State Design pattern - Real time example [TV Remote]



















    State Design pattern - Real time example [TV Remote]




















    See also:

  • State Design pattern - Introduction
  • State Design pattern - Real time example [ATM]
  • State Design pattern - Real time example [Vending Machine]
  • State Design pattern - Real time example [Project]
  • State Design pattern - Class Diagram
  • State Design pattern - Implementation [ATM]
  • State Design pattern - Implementation [Vending Machine]
  • State Design pattern - Implementation [Project]
  • State Design pattern - Implementation [LED TV]
  • State Design pattern - Keypoints
  • All Design Patterns Links
  • State Design pattern - Real time example [ATM]

    Master Practical Java Architecture & Design Patterns!

    Subscribe to Ram N Java for clean coding tutorials, GoF design patterns, and real-world system implementations!

    🔔 Subscribe to Ram N Java

    The Real-Time ATM Challenge

    An Automated Teller Machine (ATM) is an intuitive real-world scenario to understand the State Design Pattern. An ATM reacts completely differently to the exact same user action depending on its current operational state:

    • No Card State: Pressing PIN numbers or requesting cash has no effect—the machine waits for an inserted card.
    • Has Card State: The card is retained while prompting for PIN entry, rejecting multiple card insertions.
    • Authorized / Correct PIN State: Cash withdrawals and balance inquiries are enabled.
    • No Cash State: Financial dispensing is disabled, prompting service alerts or maintenance.

    Implementing these state transitions using conventional nested if-else or switch-case statements leads to tangled, fragile code that is prone to errors whenever new banking operations or states are introduced.

    Architecture of the State Pattern Solution

    The State Design Pattern solves this by encapsulating each distinct machine state into its own class and delegating behavior to the active state:

    • State Interface: Outlines key operations across the ATM lifecycle, including insertCard(), ejectCard(), insertPin(), and requestCash().
    • Concrete State Classes: Classes such as NoCard, HasCard, HasPin, and NoCash implement specific behaviors for their respective states and manage transitions to the next state.
    • Context Class (ATMMachine): Manages the machine's hardware state (such as cash inventory), holds a reference to the current state object, and delegates user actions directly to it.

    Key Architectural Benefits

    Applying the State pattern to real-world ATM modeling brings substantial design benefits:

    • Elimination of Nested Conditionals: Replaces messy conditional branches with clean, polymorphic execution.
    • Single Responsibility Principle: Keeps the validation and business logic for each operational phase isolated in dedicated classes.
    • Open/Closed Principle: Adding new states (e.g., MaintenanceMode, CardStuckState) does not require altering existing state classes.

    Related Tutorials from Ram N Java


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

    Click the below Image to Enlarge
    State Design pattern - Real time example [ATM]


















    See also:

  • State Design pattern - Introduction
  • State Design pattern - Real time example [TV Remote]
  • State Design pattern - Real time example [Vending Machine]
  • State Design pattern - Real time example [Project]
  • State Design pattern - Class Diagram
  • State Design pattern - Implementation [ATM]
  • State Design pattern - Implementation [Vending Machine]
  • State Design pattern - Implementation [Project]
  • State Design pattern - Implementation [LED TV]
  • State Design pattern - Keypoints
  • All Design Patterns Links
  • State Design pattern - Introduction

    Master Core Java Architecture & Design Patterns!

    Subscribe to Ram N Java for clean code principles, GoF design patterns, and step-by-step software engineering tutorials!

    🔔 Subscribe to Ram N Java

    What is the State Design Pattern?

    The State Design Pattern is a behavioral design pattern cataloged by the Gang of Four (GoF). It allows an object to alter its behavior when its internal state changes, making it appear as if the object has dynamically changed its class.

    In software systems, domain objects often behave differently depending on their status. For example, a document behaves differently in Draft, Moderation, and Published states. When actions are triggered, traditional approaches rely on massive conditional ladders (if-else or switch-case statements), resulting in fragile and tangled code.

    Core Concepts & Participants

    The State pattern resolves this complexity by turning states into separate polymorphic classes:

    • Context: The primary interface for clients. It maintains a reference to a concrete state object that represents the current state of the machine or process and delegates state-specific requests to it.
    • State Interface: An interface declaring the methods that all concrete state implementations must fulfill.
    • Concrete State Classes: Individual classes that implement the State interface, providing state-specific logic and coordinating state transitions.

    Why Use the State Pattern?

    Integrating the State design pattern into your applications offers key architectural advantages:

    • Elimination of Massive Conditionals: Replaces bloated conditional blocks with clean polymorphic dispatch.
    • Single Responsibility Principle: Organizes behavior corresponding to particular states into dedicated, easily testable classes.
    • Open/Closed Principle: Lets you introduce new states without modifying existing state classes or the context.

    Related Tutorials from Ram N Java


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

    Click the below Image to Enlarge
    State Design pattern - Introduction















    State Design pattern - Introduction



















    See also:

  • State Design pattern - Real time example [ATM]
  • State Design pattern - Real time example [TV Remote]
  • State Design pattern - Real time example [Vending Machine]
  • State Design pattern - Real time example [Project]
  • State Design pattern - Class Diagram
  • State Design pattern - Implementation [ATM]
  • State Design pattern - Implementation [Vending Machine]
  • State Design pattern - Implementation [Project]
  • State Design pattern - Implementation [LED TV]
  • State Design pattern - Keypoints
  • All Design Patterns Links
  • Newer Posts Older Posts Home

    Tutorials