노현진's Blog

Command Pattern

Command Pattern에 대해 설명하는 페이지입니다.

Posted
Preview Image
By HyunJinNo

Tags

Design Pattern, Java

1. Introduction

  • Purpose
    • Encapsulates a request as an object
    • This allows the request to be handled in traditionally object based relationships such as queuing and callbacks.
  • Use When
    • Requests need to be specified, queued, and executed at variant times or in variant orders.
    • A history of requests is needed.
    • The invoker should be decoupled from the object handling the invocation.

2. How to Use (Example)

  • Command Interface

    java
    1public interface Command {
    2    public void execute();
    3}
  • Implementing a command

    java
    1public class MyCommand implements Command {
    2    MyReceiver myRecevier;
    3
    4    public MyCommand(MyReceiver myReceiver) {
    5        this.myReceiver = myReceiver;
    6    }
    7
    8    public void execute() {
    9        // Call a method of myReceiver
    10        // ex. myReceiver.work();
    11    }
    12}
  • Building Invoker

    java
    1public class MyInvoker {
    2    Command slot;
    3
    4    public MyInvoker() {}
    5
    6    public void setCommand(Command command) {
    7        slot = command;
    8    }
    9
    10    // Use your own method
    11    public void buttonPressed() {
    12        slot.execute();
    13    }
    14}
  • Client Program

    java
    1public class Main {
    2    public static void main(String[] args) {
    3        // Create invoker
    4        MyInvoker myInvoker = new MyInvoker();
    5
    6        // Create receiver
    7        MyReceiver myReceiver = new MyReceiver();
    8
    9        // Create command
    10        MyCommand myCommand = new MyCommand(myReceiver);
    11
    12        // linking the invoker with the command
    13        myInvoker.setCommand(myCommand);
    14
    15        myInvoker.buttonPressed();
    16    }
    17}

© HyunJinNo. Some rights reserved.