Factory Method

Intent

Define an interface for creating an object, but let subclasses decide which class to instantiated. Factory Method lets a class defer instantiation to subclasses.

Class diagram of the original GoF pattern

structure-GoF:factorymethod

Another solution in MixJuice

Solved Problem(s)

Type safety problem
The original GoF pattern requires downcast from Product to a ConcreteProduct in order to invoke the specific methods of the ConcreteProduct. (This problem is not mentioned in the GoF book.)
Complexity problem
The class structure of the original GoF pattern is complicated. (This problem is mentioned at p.113,line.1-3 in the GoF book.)

Used programming technique(s)

Implementation selection for Product and Creator.

Consequences

Structure and pseudo code

structure:factorymethod_sample1

module m {
  define class Product {
    define abstract Product();
  }
  define class Creator {
    define Product product;
    define void anOperation() { ... product = new Product(); ... }
  }
}

module m.implementation extends m {
  class Product {
    Product() {...}
    define void concreteMethod() {...}
  }
  class Creator {
    define void anotherOperation() {
      ...
      product.concreteMethod(); // no need to cast.
      ...
    }
  }
}

Akira TANAKA <akr@m17n.org>, Yuuji ICHISUGI <y-ichisugi@aist.go.jp>

Top