Showing posts with label Command Pattern. Show all posts
Showing posts with label Command Pattern. Show all posts

Sunday, 9 February 2014

Command Design pattern - Implementation [Menu]

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 Menu Invocation Challenge

In graphical user interfaces (GUIs) or interactive console menus, user interactions such as clicking a menu item or pressing a shortcut must trigger specific business actions (such as opening a file, saving changes, or printing a document).

Hardcoding receiver logic directly inside UI menu components tightly couples the user interface to domain actions. If you tie menu items directly to specific classes, reusing actions across different UI triggers (like toolbar icons, context menus, or keyboard shortcuts) becomes difficult and error-prone.

Architecture of the Command Pattern Solution

The Command Design Pattern solves this tight coupling by turning user requests into standalone objects. In this menu implementation, the system is structured around four core participants:

  • Command Interface: Declares an execution method (typically execute()) common to all menu commands.
  • Concrete Commands: Encapsulate a binding between an action and a receiver. When execute() is called, the command invokes the appropriate method on the receiver object.
  • Invoker (Menu / MenuItem): Holds a reference to a command and triggers it when a user action occurs, remaining completely agnostic of the receiver's underlying logic.
  • Receiver: Contains the actual business logic to perform the requested operation (such as document editing, file storage, or rendering).

Key Architectural Benefits

Applying the Command pattern to menu systems provides distinct design advantages:

  • Decoupled Invoker and Receiver: The menu component only knows how to execute a command, without depending directly on concrete receiver classes.
  • Open/Closed Principle: Add new menu items and custom actions by introducing new command classes without altering existing menu code.
  • Reusable Actions: Bind the same command instance to multiple UI controls (such as a top-level menu bar, a right-click context menu, and a keyboard shortcut).

Related Tutorials from Ram N Java


Click here to watch in Youtube : https://www.youtube.com/watch?v=04iqkBZe-JE

Click the below Image to Enlarge
Command Design pattern - Implementation [Menu]

Command Design pattern - Implementation [Menu]
Command Design pattern - Implementation [Menu] - Class Diagram

WordDocument.java

/*
 *  Receiver
 */

public class WordDocument
{
public void open()
{
System.out.println("Document Opened");
}

public void save()
{
System.out.println("Document Saved");
}

public void close()
{
System.out.println("Document Closed");
}

}

Command.java

public interface Command
{
public void execute();
}

OpenCommand.java

public class OpenCommand implements Command
{
private WordDocument wordDocument;

public OpenCommand( WordDocument wordDocument )
{
this.wordDocument = wordDocument;
}

@Override
public void execute()
{
wordDocument.open();
}
}

SaveCommand.java

public class SaveCommand implements Command
{

private WordDocument wordDocument;

public SaveCommand( WordDocument wordDocument )
{
this.wordDocument = wordDocument;
}

@Override
public void execute()
{
wordDocument.save();
}
}


CloseCommand.java

public class CloseCommand implements Command
{
private WordDocument wordDocument;

public CloseCommand( WordDocument wordDocument )
{
this.wordDocument = wordDocument;
}

@Override
public void execute()
{
wordDocument.close();
}
}


MenuOptions.java

/*
 *  Invoker
 */

public class MenuOptions
{
private Command openCommand;
private Command saveCommand;
private Command closeCommand;

public MenuOptions( Command open, Command save, Command close )
{
this.openCommand = open;
this.saveCommand = save;
this.closeCommand = close;
}

public void clickOpen()
{
openCommand.execute();
}

public void clickSave()
{
saveCommand.execute();
}

public void clickClose()
{
closeCommand.execute();
}
}

Client.java

public class Client
{
public static void main( String[] args )
{
WordDocument wordDocument = new WordDocument();
Command openCommand = new OpenCommand(wordDocument);
Command saveCommand = new SaveCommand(wordDocument);
Command closeCommand = new CloseCommand(wordDocument);
MenuOptions menu = new MenuOptions(openCommand, saveCommand, closeCommand);
menu.clickOpen();
menu.clickSave();
menu.clickClose();
}

}

Output

Document Opened
Document Saved
Document Closed

See also:

  • Command Design pattern - Introduction
  • Command Design pattern - Real time example [Hotel]
  • Command Design pattern - Real time example [Menu]
  • Command Design pattern - Class Diagram
  • Command Design pattern - Sequence Diagram
  • Command Design pattern - Object Creation and flow
  • Command Design pattern - Key points
  • All Design Patterns Links
  • Command Design pattern - Real time example [Menu]

    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 Menu Invocation Challenge in Real-World Systems

    In software design, user interfaces frequently present menus with various interactive options—such as Open, Save, Cut, or Paste. When an end-user clicks an option, an underlying operation must execute.

    If the UI menu component directly instantiates and calls business logic classes, the user interface becomes tightly coupled to specific domain operations. Any change in the business layer breaks the UI, and reusing the same action across different entry points (such as toolbar buttons, context menus, and keyboard shortcuts) leads to duplicated, brittle code.

    How the Command Pattern Solves This

    The Command Design Pattern solves this tight coupling by turning each user request into a standalone object, separating the object that invokes the request from the one that knows how to execute it:

    • Command Interface: Declares an execution contract, typically an execute() method.
    • Concrete Commands: Encapsulate bindings between actions and the target receivers (e.g., OpenFileCommand, SaveFileCommand). When invoked, they simply trigger the appropriate method on the receiver.
    • Invoker (Menu / MenuItem): Holds a reference to a command object and triggers it on user interaction without knowing anything about the receiver's internal logic.
    • Receiver: Contains the actual business operations to perform the requested task (such as document file operations or graphics rendering).

    Key Architectural Benefits

    Structuring your menu workflows with the Command pattern provides crucial software engineering benefits:

    • Decoupled Invoker and Receiver: The menu system invokes operations abstractly without binding directly to complex business components.
    • Open/Closed Principle: Introduce new menu actions or custom commands without modifying existing invoker classes or client code.
    • Reusability & Extensibility: Connect the same command object to multiple invokers (menu bar items, buttons, or hotkeys) and easily support undo/redo capabilities or operation queues.

    Related Tutorials from Ram N Java


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

    Click the below Image to Enlarge
    Command Design pattern - Real time example [Menu]

    Command Design pattern - Real time example [Menu]


    See also:

  • Command Design pattern - Introduction
  • Command Design pattern - Real time example [Hotel]
  • Command Design pattern - Class Diagram
  • Command Design pattern - Sequence Diagram
  • Command Design pattern - Object Creation and flow
  • Command Design pattern - Implementation [Menu]
  • Command Design pattern - Key points
  • All Design Patterns Links
  • Thursday, 6 February 2014

    Command Design pattern - Key points

    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

    Core Summary of the Command Design Pattern

    The Command Design Pattern is a behavioral design pattern cataloged by the Gang of Four (GoF) that turns a request into a stand-alone object containing all information about the request. This transformation lets you pass requests as method arguments, delay or queue a request's execution, and support undoable operations.

    At its heart, the Command pattern establishes a clean boundary between the object that initiates an operation (the Invoker) and the object that understands how to perform it (the Receiver).

    Essential Takeaways & Structural Rules

    When applying or reviewing the Command design pattern in Java enterprise applications, keep these crucial takeaways in mind:

    • Total Decoupling: The Invoker interacts solely through the abstract Command interface (e.g., calling execute()), remaining completely unaware of concrete receivers and their domain methods.
    • Encapsulation of Requests: A command object binds together the receiver, the method to call, and any runtime parameters required to perform the action.
    • Undo/Redo & History Stacks: Because commands are self-contained objects, maintaining a stack of executed commands enables robust undo/redo mechanisms by adding an undo() method.
    • Macro Commands & Queuing: Commands can be grouped into composite macros or stored in task queues, schedulers, and thread pools for deferred or asynchronous execution.

    Architectural Advantages & Considerations

    Evaluating the architectural impact of the Command pattern helps balance code flexibility and structure:

    • Single Responsibility Principle: Decouples classes that invoke operations from classes that perform these operations.
    • Open/Closed Principle: You can introduce new commands into the application without breaking existing client or invoker code.
    • Design Trade-off: Encapsulating every operation into a dedicated class can increase the overall number of classes in simple systems, so ensure the added flexibility is warranted.

    Related Tutorials from Ram N Java


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

    Click the below Image to Enlarge





    See also:

  • Command Design pattern - Introduction
  • Command Design pattern - Real time example [Hotel]
  • Command Design pattern - Real time example [Menu]
  • Command Design pattern - Class Diagram
  • Command Design pattern - Sequence Diagram
  • Command Design pattern - Object Creation and flow
  • Command Design pattern - Implementation [Menu]
  • All Design Patterns Links
  • Command Design pattern - Real time example [Hotel]

    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-World Hotel Food Ordering Problem

    To grasp behavioral design patterns intuitively, consider the everyday real-time workflow of dining at a restaurant or hotel:

    • A Customer reviews the menu and places an order with the Waiter.
    • The Waiter writes down the order details on an order slip (the command) and passes it to the kitchen.
    • The Cook / Chef receives the order slip and prepares the dish according to the specifications.

    Notice that the customer never walks directly into the kitchen to instruct the chef how to cook, nor does the waiter cook the meal. If we design software where the client directly invokes the kitchen's low-level cooking methods, the system becomes tightly coupled, rigid, and impossible to scale or automate with queues and order histories.

    Mapping the Hotel System to Command Pattern Components

    The Command Design Pattern neatly models this restaurant scenario by turning the customer's request into a standalone object:

    • Client: The customer who decides what dish they want to order.
    • Command Interface: Declares the contract (such as execute()) that triggers the order processing.
    • Concrete Command (Order): Encapsulates the specific dish request and holds a reference to the receiver (the Chef). Calling execute() tells the chef to prepare the dish.
    • Invoker (Waiter): Receives the order object, tracks it, and invokes execute() when handing it over to the kitchen.
    • Receiver (Chef / Kitchen): Possesses the actual cooking instructions and domain knowledge required to prepare the meal.

    Key Architectural Benefits

    Modeling the food ordering workflow using the Command pattern delivers essential software architecture benefits:

    • Decoupling Invoker and Receiver: The waiter doesn't need to know cooking recipes; the waiter only needs to route the order command.
    • Queueing and Scheduling: Orders can be lined up in queues, batched, delayed, or prioritized across kitchen workstations.
    • Extensibility & SOLID Principles: Introducing new menu items or special preparation commands requires no changes to the waiter or client classes.

    Related Tutorials from Ram N Java


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

    Click the below Image to Enlarge
    Command Design pattern - Real time example [Hotel]

















    See also:

  • Command Design pattern - Introduction
  • Command Design pattern - Real time example [Menu]
  • Command Design pattern - Class Diagram
  • Command Design pattern - Sequence Diagram
  • Command Design pattern - Object Creation and flow
  • Command Design pattern - Implementation [Menu]
  • Command Design pattern - Key points
  • All Design Patterns Links
  • Wednesday, 5 February 2014

    Command Design pattern - Object Creation and flow

    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 & Object Creation in Command Pattern

    Understanding the Command Design Pattern requires looking closely at who instantiates which object and how these objects interact across runtime boundaries. In traditional tightly coupled designs, caller objects directly create and trigger receiver dependencies, making it difficult to decouple the initiator from execution logic.

    In the Command pattern, object creation is clearly segmented: the Client instantiates the receiver and passes it into the constructor of a concrete command object. The client then registers this configured command object with the Invoker.

    Step-by-Step Execution Flow

    The interaction flow across the participants follows a precise sequence:

    1. Initialization: The Client instantiates the Receiver (the business logic component).
    2. Command Binding: The Client creates the ConcreteCommand object, injecting the receiver reference into it.
    3. Invoker Configuration: The Client assigns the command object to the Invoker (e.g., UI button, scheduler, or queue).
    4. Triggering: When an event occurs, the Invoker calls command.execute() without any awareness of who the receiver is or what action will occur.
    5. Execution: Inside execute(), the ConcreteCommand forwards the execution call to the underlying receiver.action() method.

    Key Architectural Benefits

    Following this structured flow provides critical software engineering advantages:

    • Complete Separation of Concerns: The invoker has zero compile-time or runtime coupling to specific business receivers.
    • Configurable Runtime Behavior: Commands can be dynamically swapped or parameterized during application runtime without code changes.
    • Support for Asynchronous & Queued Execution: Because the request is a fully realized object, it can be scheduled, stored in a queue, or executed across thread boundaries.

    Related Tutorials from Ram N Java


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

    Click the below Image to Enlarge
    Command Design pattern - Object Creation and flow


















    See also:

  • Command Design pattern - Introduction
  • Command Design pattern - Real time example [Hotel]
  • Command Design pattern - Real time example [Menu]
  • Command Design pattern - Class Diagram
  • Command Design pattern - Sequence Diagram
  • Command Design pattern - Implementation [Menu]
  • Command Design pattern - Key points
  • All Design Patterns Links
  • Command Design pattern - Sequence Diagram

    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

    Understanding the Runtime Interaction in Command Pattern

    While a class diagram captures static relationships, understanding how objects communicate over time is critical when designing decoupled systems. In the Command Design Pattern, tracing runtime message exchanges through a Sequence Diagram highlights exactly how requests move from creation to execution without tight coupling.

    By visualizing lifelines and synchronous method calls, developers can clearly see the separation of duties between the entity setting up operations, the caller triggering requests, and the receiver executing actual domain tasks.

    Step-by-Step Message Flow in the Sequence Diagram

    The sequence diagram traces a clean five-stage lifecycle across the participating lifelines:

    1. Receiver Instantiation: The Client lifeline initializes the Receiver object, which holds domain-specific business actions.
    2. Command Construction: The Client instantiates the ConcreteCommand object, passing the Receiver reference into its constructor.
    3. Invoker Configuration: The Client calls a setter method (such as setCommand(command)) on the Invoker lifeline, wiring the command for later execution.
    4. Execution Invocation: When triggered by an event, the Invoker calls execute() on the ConcreteCommand lifeline, requiring no knowledge of the underlying receiver.
    5. Action Delegation: In response to execute(), the ConcreteCommand invokes action() on the Receiver lifeline to carry out the core operation.

    Key Architectural Benefits

    Visualizing the Command pattern interaction sequence emphasizes key software engineering benefits:

    • Temporal Decoupling: The command can be created and stored in the invoker at one point in time and executed much later or in a separate thread.
    • Total Isolation of the Invoker: The sequence demonstrates that the invoker interacts solely with the Command interface, ensuring zero compile-time dependencies on the receiver.
    • Extensibility: New commands and flows can be inserted into the sequence without modifying client or invoker interaction patterns.

    Related Tutorials from Ram N Java


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

    Click the below Image to Enlarge
    Command Design pattern - Sequence Diagram 

















    See also:

  • Command Design pattern - Introduction
  • Command Design pattern - Real time example [Hotel]
  • Command Design pattern - Real time example [Menu]
  • Command Design pattern - Class Diagram
  • Command Design pattern - Object Creation and flow
  • Command Design pattern - Implementation [Menu]
  • Command Design pattern - Key points
  • All Design Patterns Links
  • Command Design pattern - Class Diagram

    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

    Structural Overview of the Command Pattern

    The Command Design Pattern is a behavioral design pattern cataloged by the Gang of Four (GoF) that encapsulates a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.

    To understand how this decoupling is achieved in object-oriented systems, analyzing the UML Class Diagram is essential. It defines clear boundaries between the entity that triggers an action, the abstraction representing the action, and the component that performs the actual business operation.

    Class Diagram Participants & Relationships

    The UML structure of the Command pattern is composed of five central participants:

    • Command (Interface): Declares the abstract execution method, typically execute() (and optionally undo()).
    • ConcreteCommand: Implements the Command interface. It maintains a reference to the Receiver and defines the binding by calling the corresponding operation on the receiver when execute() is invoked.
    • Invoker: Holds a reference to a Command object (via composition or aggregation) and asks the command to carry out the request by calling its execute() method.
    • Receiver: Knows how to perform the operations associated with carrying out the request. Any class can serve as a receiver.
    • Client: Creates a ConcreteCommand object, binds it to a Receiver, and assigns it to an Invoker.

    Architectural Benefits Reflected in the Diagram

    The structural arrangement depicted in the class diagram provides critical design advantages:

    • Loose Coupling: The Invoker has no compile-time dependency on concrete receivers; it only interacts with the generic Command abstraction.
    • Open/Closed Principle: You can add new concrete command implementations without modifying existing invokers, receivers, or client code.
    • High Cohesion: Each command class encapsulates only the logic required to invoke a specific business action on its target receiver.

    Related Tutorials from Ram N Java


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

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


















    See also:

  • Command Design pattern - Introduction
  • Command Design pattern - Real time example [Hotel]
  • Command Design pattern - Real time example [Menu]
  • Command Design pattern - Sequence Diagram
  • Command Design pattern - Object Creation and flow
  • Command Design pattern - Implementation [Menu]
  • Command Design pattern - Key points
  • All Design Patterns Links
  • Tuesday, 4 February 2014

    Command 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 Command Design Pattern?

    The Command Design Pattern is a foundational behavioral pattern established by the Gang of Four (GoF). Its primary intent is to encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.

    In conventional software architectures, user interfaces or calling components often invoke business operations directly. This tight coupling means that any change to the business layer requires rewriting UI triggers, and features like command queuing, scheduling, or history tracking become challenging to implement.

    Core Concepts & Participants

    The Command pattern solves this coupling by separating the object that invokes the command from the object that receives and executes it:

    • Command Interface: Declares an execution method (typically execute()) common to all concrete operations.
    • Concrete Command: Implements the Command interface, maintaining a reference to the receiver and delegating execution to the receiver's specific methods.
    • Invoker: Asks the command to carry out the request (e.g., a button, menu item, or remote control) without knowing which receiver handles it.
    • Receiver: Knows how to perform the actual business logic necessary to carry out the requested action.
    • Client: Creates and configures concrete command objects and binds them to the appropriate invokers.

    Key Architectural Benefits

    Introducing the Command pattern into your design offers notable software engineering advantages:

    • Decoupling Invoker and Receiver: Classes invoking operations are completely isolated from classes that execute them.
    • Single Responsibility Principle: Classes that trigger operations are kept separate from classes that implement domain logic.
    • Open/Closed Principle: New commands can be introduced seamlessly without altering existing client or invoker code.

    Related Tutorials from Ram N Java


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

    Click the below Image to Enlarge
    Command Design pattern - Introduction

    Command Design pattern - Introduction


    See also:

  • Command Design pattern - Real time example [Hotel]
  • Command Design pattern - Real time example [Menu]
  • Command Design pattern - Class Diagram
  • Command Design pattern - Sequence Diagram
  • Command Design pattern - Object Creation and flow
  • Command Design pattern - Implementation [Menu]
  • Command Design pattern - Key points
  • All Design Patterns Links
  • Older Posts Home

    Tutorials