Sunday, May 03, 2009

Factory Method/Virtual Constructor


Define an interface for creating an object, but let subclass decide which class to instantiate.

Motivation: Frameworks use abstract classes to define and maintain relationships between objects. Frameworks are often responsible for creating objects.

image

Here, Application and Document are abstract classes. Now application is responsible is responsible for creating a document, but which document???

While working you will have a instance of concrete application pointed by abstract Application, now you call a Factory Method (NewDocument in our case) on the Application which in turn calls CreateDocument on concrete application – this now knows what to return –> based on itself.

Consequence:

  • You get a hook at subclass
  • You can connect parallel class hierarchy

You can use templates if you want to avoid subclass
You can take in a parameter in Factory Method and decide which class to instantiate
You might want to create object pool
You can name constructor private or protected

Factory method requests for object creating, new forces

Called within Template Method
This is creation through inheritance
Prototype is creation through delegation

No comments: