Composite Commands


Consider our discussion of Sensors and Command objects in Chapter 21. Figure 21-3 showed a Sensor class using a Command class. On detecting its stimulus, the Sensor called Do() on the Command.

What I failed to mention then was that often, a Sensor had to execute more than one Command. For example, when it reached a certain point in the paper path, the paper would trip an optical sensor. That sensor then stopped a motor, started another, and engaged a particular clutch.

At first, we took this to mean that every Sensor class would have to maintain a list of Command objects (see Figure 31-2). However, we soon recognized that whenever it needed to execute more than one Command, a Sensor always treated those Command objects identically. That is, it simply iterated over the list and called Do() on each Command. This was ideal for the COMPOSITE pattern.

Figure 31-2. Sensor containing many Commands


So we left the Sensor class alone and created a CompositeCommand, as shown in Figure 31-3. This meant that we didn't have to change the Sensor or the Command. We were able to add the plurality of Commands to a Sensor without changing either. This is an application of OCP.

Figure 31-3. CompositeCommand





Agile Principles, Patterns, and Practices in C#
Agile Principles, Patterns, and Practices in C#
ISBN: 0131857258
EAN: 2147483647
Year: 2006
Pages: 272

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net