Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
Chapter 7 CHAPTER 7 Command Pattern 7 To command is to serve, nothing more and nothing less. --Andre Malraux When you do the common things in life in an uncommon way, you will command the attention of the world. --George Washington Carver Create like a god, command like a king, work like a slave. --Constantin Brancusi What Is the Command Pattern? The command pattern allows a client to issue requests to an object without making any assumptions about the request, or the receiving object. Think of the request as a command sent to an object to engage in a known behavior. The straightforward way to do this would be to create an instance of the object, and call the method that implements the required command (or behavior). For example, let's assume that we're building a house that allows computer control of many of its components such as lights, doors, heating, etc. Let's look at the code that would turn on a light bulb. The Light class implements a method called on( ) that turns on a light. A client would execute the following code to turn the light on. var light = new Light( ); light.on( ); Let's look at another command to open a door. In this case, the receiver of the com- mand is an instance of the Door class, which implements a method called open( ) that opens the front door. var frontdoor = new Door( ); frontdoor.open( ); 247