커맨드패턴 (1)

Creational Patterns ( 생성 패턴 )

These design patterns provides way to create objects while hiding the creation logic, rather than instantiating objects directly using new operator. This gives program more flexibility in deciding which objects need to be created for a given use case. 

생성패턴은 객체의 생성로직을 숨기고 new 명령어를 통하지 않고 객체를 생성하는 방법들을 제공한다. 이는 특정 상황에서 어떤 방법으로 객체를 생성해야할지를 결정하는데 있어서 유연성을 제공한다. 


 Structural Patterns ( 구조적 패턴 )

These design patterns concern class and object composition. Concept of inheritance is used to compose interfaces and define ways to compose objects to obtain new functionalities. 

구조적 패턴들은 클래스와 객체의 구성에 관여한다.

 

 Behavioral Patterns ( 행위적 패턴 )

These design patterns are specifically concerned with communication between objects.

이 패턴들은 객체들 사이의 커뮤니케이션에 관심을 가진다.

 

오늘 살펴볼  Command ( 명령, 커맨드 )패턴은 Behavioral 패턴에 속한다.   

명령 패턴이라~ 명령을 내리는 패턴이라는 거겠죠??

자세히 알아봅시다.

 

Command Pattern Structure

 


 


  

패턴의 목적 ( Intent ) :  

Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.  

명령 패턴, 커맨드 패턴은 하나의 요청을 하나의 객체로 캡슐화하여 요청을 파라미터처럼 사용할 수 있게끔 해주며 되돌리기 기능을 지원한다. 


패턴이 나오게 된 동기 ( Motivation ) :

   Need to issue requests to objects without knowing anything about the operation being requested or the receiver of the request.

이 패턴이 나오게 된 동기라 하면 간단히 말해서 요청을 날릴 때 어떤 요청이 날아가는지 리시버가 누구인지에 대해서 몰라도 되게끔 하기 위해서 입니다.  

 

GoF의 디자인 패턴에서는 응용프로그램의 메뉴를 클릭했을 때 어떤 명령을 실행하는 것을 예로 들었습니다.


 위 클래스 다이어그램은 응용프램에서 메뉴를 선택해서 들어가고 하위메뉴를 클릭했을 때 특정 명령이 실행되는 것을 나타내고 있습니다.메뉴아이템은 커맨드 객체를 가지고 있고 이 커맨드 객체는 실행할 수 있는 기능이 구현되어 있을 것입니다. 메뉴아이템객체는 이 커맨드객체가 무슨 명령을 실행하는 지는 모르고 그냥 실행만 시키는 겁니다. 

 

유용성 ( Applicability ) :

Use the Command pattern when you want to

명령 패턴은 이럴 때 쓰세요. 

parameterize objects by an action to perform, as MenuItem objects did above. You can express such parameterization in a procedural language with a callback function, that is, a function that's registered somewhere to be called at a later point. Commands are an object-oriented replacement for callbacks.  

 

• specify, queue, and execute requests at different times. A Command object can have a lifetime independent of the original request. If the receiver of a request can be represented in an address space-independent way, then you can transfer a command object for the request to a different process and fulfill the request there.

 

• support undo. The Command's Execute operation can store state for reversing its effects in the command itself. The Command interface must have an added Unexecute operation that reverses the effects of a previous call to Execute. Executed commands are stored in a history list. Unlimited-level undo and redo is achieved by traversing this list backwards and forwards calling Unexecute and Execute, respectively.

 

• support logging changes so that they can be reapplied in case of a system crash. By augmenting the Command interface with load and store operations, you can keep a persistent log of changes. Recovering from a crash involves reloading logged commands from disk and reexecuting them with the Execute operation.

 

• structure a system around high-level operations built on primitives operations. Such a structure is common in information systems that support transactions. A transaction encapsulates a set of changes to data. The Command pattern offers a way to model transactions. Commands have a common interface, letting you invoke all transactions the same way. The pattern also makes it easy to extend the system with new transactions.



등장 인물 ( Participants ) :


Command

o declares an interface for executing an operation.  

ConcreteCommand

o defines a binding between a Receiver object and an action.

o implements Execute by invoking the corresponding operation(s) on Receiver.

Client 

           o creates a ConcreteCommand object and sets its receiver.
Invoker

           o asks the command to carry out the request.
Receiver

           o
knows how to perform the operations associated with carrying out a request. Any class may serve as a Receiver.


원리 ( Collaborations ) :

  • The client creates a ConcreteCommand object and specifies its receiver.
  • An Invoker object stores the ConcreteCommand object.
  • The invoker issues a request by calling Execute on the command. When commands are undoable, ConcreteCommand stores state for undoing thecommand prior to invoking Execute.

  • The ConcreteCommand object invokes operations on its receiver to carryout the request.

 

The following diagram shows the interactions between these objects.It illustrates how Command decouples the invoker from the receiver(and the request it carries out).

 

 


패턴 사용법

  1. Define a Command interface with a method signature like execute().
  2. Create one or more derived classes that encapsulate some subset of the following: a "receiver" object, the method to invoke, the arguments to pass.
  3. Instantiate a Command object for each deferred execution request.
  4. Pass the Command object from the creator (aka sender) to the invoker (aka receiver).
  5. The invoker decides when to execute().

패턴 사용의 장단점 ( Consequences ): 

The Command pattern has the following consequences:  

  1. Command decouples the object that invokes the operation from the one that knows how to perform it.
  2. Commands are first-class objects.They can be manipulated and extended like any other object.
  3. You can assemble commands into a composite command. In general, composite commands are an instance of the Composite pattern.
  4. It's easy to add new Commands, because you don't have to change existing classes.

관련 패턴들 :  

A Composite can be used to implement MacroCommands.
A Memento can keep state the command requires to undo its effect.

A command that must be copied before being placed on the historylist acts as a Prototype.


추가 정보 :     

  • Chain of Responsibility, Command, Mediator, and Observer, address how you can decouple senders and receivers, but with different trade-offs. Command normally specifies a sender-receiver connection with a subclass.
  • Chain of Responsibility can use Command to represent requests as objects.
  • Command and Memento act as magic tokens to be passed around and invoked at a later time. In Command, the token represents a request; in Memento, it represents the internal state of an object at a particular time. Polymorphism is important to Command, but not to Memento because its interface is so narrow that a memento can only be passed as a value.
  • Command can use Memento to maintain the state required for an undo operation.
  • MacroCommands can be implemented with Composite.
  • A Command that must be copied before being placed on a history list acts as a Prototype.
  • Two important aspects of the Command pattern: interface separation (the invoker is isolated from the receiver), time separation (stores a ready-to-go processing request that's to be stated later).

 

출처 :  http://sourcemaking.com/design_patterns/command

Design Patterns : Element of Reusable Object Oriented Software ( by GoF, 1994 )