Problem

Within the standardized model context of a framework, we need to provide for the instantiation of is internal objects.

Solution

Define an interface for instantiation. Defer instantiation to subclasses when appropriate.

Related Patterns

Discussion

The added complexity of Factory object instantiation adds a great deal of customization to a design. Factory is unnecessary if the class of the created object never changes or if the initialization is easily overridden.

Examples

The Factory pattern draws its name from an actual factory - which is a great example of the Factory pattern. Base materials enter and final products leave. The type of final product created depends on the internal workings of the factory itself.

Code

This is a simple example of a Factory Method in C++. Fubar::make_fubar() returns a proper new instance of the subtype that you select in the main loop.

class Fubar{
public:
  static Fubar *make_fubar(int c);
  virtual void print_name();
}

int main(){
  vector fubars;
  int choice;
  while(1){
    cout << "Foo(1) Bar(2) or Quux(3)? Do(0) ";
    cin >> choice;
    if(!choice) break;
    fubars.push(Fubar::make_fubar(choice));
  }
  for(int i = 0; i < roles.size(); i++) fubars[i]->print_name();
  for(int i = 0; i < roles.size(); i++) delete fubars[i];
}

class Foo: public Fubar{
public:
  void print_name(){cout << "Foo" << endl;}
}
class Bar: public Fubar{
public:
  void print_name(){cout << "Bar" << endl;}
}
class Quux: public Fubar{
  public:
  void print_name(){cout << "Quux" << endl;}
}

Fubar *Fubar::make_fubar(int c){
  if(c == 1) return new Foo;
  else if(c == 2) return new Bar;
  else return new Quux;
}