Command Pattern - Example

Example

Consider a "simple" switch. In this example we configure the Switch with two commands: to turn the light on and to turn the light off.

A benefit of this particular implementation of the command pattern is that the switch can be used with any device, not just a light - the Switch in the following example turns a light on and off, but the Switch's constructor is able to accept any subclasses of Command for its two parameters. For example, you could configure the Switch to start an engine.

Note: A criticism of the sample application below is that it doesn't truly model an electrical circuit. An electrical switch is dumb. A true binary switch knows only that it is either on or off. It does not know about or have any direct relationship with the various loads that might be attached to a circuit (i.e. you hook up a switch to a circuit, not directly to a load). The switch should simply publish an event of its current state (either an ON or OFF). The circuit then should contain a State Engine that manages circuit states at various points along it (by listening to switch events) in order to properly accommodate complex circuits with multiple loads and switches. Each load is then conditional to a specific circuit's state (not directly to any specific switch). In conclusion, the switch itself should not be aware of any lamp details.

Read more about this topic:  Command Pattern

Famous quotes containing the word example:

    Our intellect is not the most subtle, the most powerful, the most appropriate, instrument for revealing the truth. It is life that, little by little, example by example, permits us to see that what is most important to our heart, or to our mind, is learned not by reasoning but through other agencies. Then it is that the intellect, observing their superiority, abdicates its control to them upon reasoned grounds and agrees to become their collaborator and lackey.
    Marcel Proust (1871–1922)