title: Factory Method pattern vs composition
body: <p>From GoF chapter about the Factory Method pattern:</p>
  
  <blockquote>
    <p>Define an interface for creating an object, but <strong>let subclasses decide which class to
    instantiate</strong>. Factory Method lets a class defer instantiation to subclasses.</p>
  </blockquote>
  
  <p>The idea is to let subclasses decided which class to instantiate, and GoF's implementation of the idea, is to provide an abstract method in the superclass, that subclasses need to override, and thus providing their own instantiation logic.</p>
  
  <p>What I don't understand is, why implementing it using an abstract method, and not using a class member which <em>is</em> the factory. I'll explain.</p>
  
  <p>This is the GoF way:</p>
  
  <pre><code>public abstract class Creator {
      public void doStuff() {
          Product product = createProduct();
          /* etc. */
      }
  
      public abstract Product createProduct();
  }
  </code></pre>
  
  <p>Usage:</p>
  
  <pre><code>    MyCreator myCreator = new Creator() {
          @Override
          public Product createProduct() {
              return new MyProduct();
          }
      }
  
      myCreator.doStuff();
  </code></pre>
  
  <p>But why bother with the subclassing, etc.? I suggest this approach:</p>
  
  <pre><code>public class Creator {
      private Factory factory;
  
      /* constructor */
      public Creator(Factory factory) {
          this.factory = factory;
      }
  
      public void doStuff() {
          Product product = factory.createProduct();
          /* etc. */
      }
  }
  </code></pre>
  
  <p>And this is how you use it:</p>
  
  <pre><code>    MyFactory myFactory = new MyFactory();
      Creator creator = new Creator(myFactory);
      creator.doStuff();
  </code></pre>
  
  <p>So what is the benefit in GoF's approach? Why not composing the <em>Factory</em> into the <em>Creator</em> class instead of expressing it using an abstract method?</p>