title: How do I correctly implement the Factory Pattern in MATLAB?
body: <p>I am writing a program in which I can select from a list of available <code>Sensor</code> objects; upon selection and user validation, the program should instantiate that <code>Sensor</code>. </p>
  
  <p>The following code snippet is what I might naively do:</p>
  
  <pre><code>switch userInput
      case 'Sensor A' 
          s = SensorA; % subclass of Sensor
  
      case 'Sensor B'
          s = SensorB; % subclass of Sensor
  
      %...
  end
  </code></pre>
  
  <p>There are some obvious problems here, but the biggest problem I have is making this extensible. I want to be able to create lots of various <code>Sensor</code> subclasses (or have other developers generate <code>Sensor</code> subclasses) without having to continuously add to this <code>switch</code> statement. More generally, I want to adhere to the <a href="http://en.wikipedia.org/wiki/Open/closed_principle" rel="nofollow">open/closed principle</a>. I ought to be able to have lots of different <code>Sensor</code> subclasses. (I also want to populate a popupmenu <code>uicontrol</code> with the available <code>Sensors</code>, but that probably gets solved if this problem gets solved generally.) Other naive solutions such as peeking into a folder full of <code>Sensor</code> subclasses doesn't work very well either, since object construction may be different for each subclass.</p>
  
  <p>I believe I'm looking to use the <a href="http://en.wikipedia.org/wiki/Factory_method_pattern" rel="nofollow">factory method pattern</a>, but I'm not entirely sure how to implement it. I could put the above code snippet into a separate <code>SensorFactory</code>, but this just moves the <code>switch</code> statement around, meaning extending it requires modifying it.</p>
  
  <p>How do I implement the factory method pattern correctly such that the factory object doesn't require modification every time I add a new <code>Sensor</code> subclass?</p>