title: Pattern for choosing behaviour based on the types present in a collection derived objects
body: <p>I have an collection of objects which represents a model of a system. Each of these objects derives from a base class which represents the abstract "component". I would like to be able to look at the system and choose certain behaviours based on what components are present and in what order.</p>
  
  <p>For the sake of argument, let's call the base class <code>Component</code> and the actual components <code>InputFilter</code>, <code>OutputFilter</code> and <code>Processor</code>. Systems that we can deal with are ones with a <code>Processor</code> and one or both filters. The actual system has more types and more complex interaction between them, but I think this will do for now.</p>
  
  <p>I can see two "simple" ways to handle this situation with a <code>marshalComponentSettings()</code> function which takes one of the collections and works out how to most efficiently set up each node. This may require modifying inputs in certain ways or splitting them up differently, so it's not quite as simple as just implementing a virtual <code>handleSettings()</code> function per component.</p>
  
  <ul>
  <li><p>The first is to report a enumerated type from each class using a pure virtual function and use those to work out what to do, <code>dynamic_cast</code>'ing where needed to access component specific options.</p>
  
  <pre><code>enum CompType {
      INPUT_FILTER,
      OUTPUT_FILTER,
      PROCESSOR
  }
  
  void marshal(Settings&amp; stg)
  {
      if (comps[0].type() == INPUT_FILTER)
          setUpInputFilter(stg); //maybe modified the stg, or provides other feedback of what was done
  
      // something similar for outputs
  
      setUpProcessor(stg);
  }
  </code></pre></li>
  <li><p>The second is to <code>dynamic_cast</code> to anything that might be an option in this function and use the success of that or not (as well as maybe the cast object if needed) to determine what to do.</p>
  
  <pre><code>void marshal(Settings&amp; stg)
  {
      if (InputFilter* filter = dynamic_cast&lt;InputFilter*&gt;(comp[0]))
          setUpInputFilter(stg); //maybe modified the stg, or provides other feedback of what was done
  
      // something similar for outputs
  
     setUpProcessor(stg);
  }
  </code></pre></li>
  </ul>
  
  <p>It seems that the first is the most efficient way (don't need to speculatively test each object to find out what it is), but even that doesn't quite seem right (maybe due to the annoying details of how those devices affect each other leaking into the general marshaling code).</p>
  
  <p>Is there a more elegant way to handle this situation than a nest of conditionals determining behaviour? Or even a name for the situation or pattern?</p>