Command Pattern
Command Pattern에 대해 설명하는 페이지입니다.
Command Pattern
Tags
Design Pattern, Java
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.
How to Use (Example)
Command Interface
1 2 3
public interface Command { public void execute(); }
Implementing a command
1 2 3 4 5 6 7 8 9 10 11 12
public class MyCommand implements Command { MyReceiver myRecevier; public MyCommand(MyReceiver myReceiver) { this.myReceiver = myReceiver; } public void execute() { // Call a method of myReceiver // ex. myReceiver.work(); } }
Building Invoker
1 2 3 4 5 6 7 8 9 10 11 12 13 14
public class MyInvoker { Command slot; public MyInvoker() {} public void setCommand(Command command) { slot = command; } // Use your own method public void buttonPressed() { slot.execute(); } }
Client Program
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
public class Main { public static void main(String[] args) { // Create invoker MyInvoker myInvoker = new MyInvoker(); // Create receiver MyReceiver myReceiver = new MyReceiver(); // Create command MyCommand myCommand = new MyCommand(myReceiver); // linking the invoker with the command myInvoker.setCommand(myCommand); myInvoker.buttonPressed(); } }
This post is licensed under CC BY 4.0 by the author.