1 of 14

Command

Christopher Ngai and Dan Fang

2 of 14

What’s Command Pattern?

The command pattern is a behavioral design pattern in which an object is used to represent and encapsulate all the information needed to call a method at a later time. This information includes the method name, the object that owns the method and values for the method parameters.

  • From http://en.wikipedia.org/wiki/Command_pattern

3 of 14

Real World Example - Restaurant

Waitress

(Command - puts order in queue)

Order Queue (Invoker - Sends order)

Chef

(Reciever - executes order)

Patron

(Client - Asks for order to be completed)

4 of 14

Objects in Command

  • Command
    • Sends command to receiver
  • Receiver
    • Performs command task
  • Invoker
    • Invokes command, bookeeps execution
  • Client
    • Contains command and invoker objects, sends command object to invoker

5 of 14

UML Diagram

6 of 14

Advantages of Command

The main advantage of the command pattern is that the invoker and receiver are low coupled objects. This means that any changes to one will not directly affect the other. Another advantage of using design patterns in general is good organization and readability in code.

7 of 14

Disadvantage of Command

The main drawback is that Command requires more objects to invoke a command than just a single method object.

8 of 14

Why/How to Implement

If you find your code using a lot of if-else statements to branch into different functions, consider using the Command Pattern.

Keys to implementing: Separate your code into an invoker, command objects, and receiver so that the code is low coupled and more readable under a client function.

9 of 14

10 of 14

11 of 14

12 of 14

13 of 14

Works Cited

"By Your Command." IdioTechie RSS. N.p., 4 Nov. 2012. Web. 13 Oct. 2014.

"Command Pattern." Wikipedia. Wikimedia Foundation, 10 Oct. 2014. Web. 13 Oct. 2014.

Ziyang, Zhang. "Command Mode Step by Step." Http://www.tracefact.net/. N.p., 20 Dec. 2007. Web.

14 of 14

Thanks for listening!

Any questions?