Design Patterns Tutorial
A tutorial on GOF design patterns. This tutorial is for beginners who are going to learn design patterns for the first time. Each pattern is expalined with suitable examples.

24/11/2013 Categories: Creational Patterns. No Comments on Factory Method Pattern

Intent:

Defines an interface for creating an object, but lets subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.

 

Also Known As:

Virtual Constructor

 

Motivation:

Take into consideration a framework for desktop applications. Such applications are meant to work with documents. A framework for desktop applications contains definitions for operations such as opening, creating and saving a document. The basic classes are abstract ones, named Application and Document, their clients having to create subclasses from them in order to define their own applications. For generating a drawing application, for example, they need to define the DrawingApplication and DrawingDocument classes. The Application class has the task of managing the documents, taking action at the request of the client (for example, when the user selects the open or save command form the menu).

Because the Document class that needs to be instantiated is specific to the application, the Application class does not know it in advance, so it doesn’t know what to instantiate, but it does know when to instantiate it. The framework needs to instantiate a certain class, but it only knows abstract classes that can’t be instantiated.

The Factory Method design pattern solves the problem by putting all the information related to the class that needs to be instantiated into an object and using them outside the framework, as you can see below:

factory method pattern motivation example

 

Applicability:

  1. A class can’t anticipate the class of objects it must create.
  2. A class wants its sub classes to specify the objects it creates.
  3. Classes delegate responsibility to one of several helper subclasses.

 

Structure:

factory method pattern structure

 

Participants:

The classes that take part in Factory Method pattern are:

Product: Defines the interface of objects the factory method creates.

ConcreteProduct: Implements the Product interface.

Creator: Declares the factory method, which returns an object of the type Product. Creator may also provide a default implementation of the factory method which returns a default ConcreteProduct object.

ConcreteCreator: Overrides the factory method to return an instance of a ConcreteProduct.

 

Collaborations:

Creator relies on its subclasses to provide an implementation for the factory method so that it returns an instance of the appropriate ConcreteProduct class.

 

Consequences:

The benefits and drawbacks of factory method pattern are as follows:

  • The main reason for which the factory pattern is used is that it introduces a separation between the application and a family of classes (it introduces weak coupling instead of tight coupling hiding concrete classes from the application). It provides a simple way of extending the family of products with minor changes in application code.
  • It provides customization hooks. When the objects are created directly inside the class it’s hard to replace them by objects which extend their functionality. If a factory is used instead to create a family of objects the customized objects can easily replace the original objects, configuring the factory to create them.
  • The factory has to be used for a family of objects. If the classes doesn’t extend common base class or interface they cannot be used in a factory design template.

 

Implementation:

All concrete products are subclasses of the Product class, so all of them have the same basic implementation, at some extent. The Creator class specifies all standard and generic behavior of the products and when a new product is needed, it sends the creation details that are supplied by the client to the ConcreteCreator. Having this diagram in mind, it is easy for us now to produce the code related to it. Here is how the implementation of the classic Factory method should look:

 

public interface Product {  }

public class ConcreteProduct implements Product {  }

public abstract class Creator 
{
	public void anOperation() 
	{
		Product product = factoryMethod();
	}	
	protected abstract Product factoryMethod();
}

public class ConcreteCreator extends Creator 
{
	protected Product factoryMethod() 
	{
		return new ConcreteProduct();
	}
}

public class Client 
{
	public static void main( String arg[] ) 
	{
		Creator creator = new ConcreteCreator();
		creator.anOperation();
	}
}

 

Sample Code:

Let’s consider a Vehicle interface and 2 of its implementations namely Car and Vehicle:

 

interface Vehicle
{
	public void drive();
	public void clean();
}

class Car implements Vehicle
{
	@Override
	public void drive()
	{
		System.out.println("Driving a car...");
	}
	@Override
	public void clean()
	{
		System.out.println("Cleaning a car...");
	}
}

class Bus implements Vehicle
{
	@Override
	public void drive()
	{
		System.out.println("Driving a Bus...");
	}
	@Override
	public void clean()
	{
		System.out.println("Cleaning a Bus...");
	}
}

And to drive() and clean() the Vehicle we would use a VehicleDriver.

Let’s consider the implementation and of VehicleDriver:

abstract class VehicleDriver 
{
	public abstract Vehicle getVehicle();
	public void driveVehicle()
	{
		getVehicle().drive();
	}
	public void cleanVehicle()
	{
		getVehicle().clean();
	}
}

class CarDriver extends VehicleDriver 
{
	@Override
	public Vehicle getVehicle()
	{
		return new Car();
	}
}

class BusDriver extends VehicleDriver 
{
	@Override
	public Vehicle getVehicle()
	{
		return new Bus();
	}
}

 

In the above VehicleDriver implementation the getVehicle() method is the factory method which is overridden by the CarDriver and Busdriver to return Car and Businstances respectively. In this way the programmer would be more concerned about using the VehicleDriver abstraction and need not be concerned about its different implementations.

factory method pattern relaworld example

 

Known Uses:

  1. Class View in the Smalltalk-80 Model/View/Controller framework has a method defaultController that creates a controller, and this might appear to be a  factory method. But subclasses of View specify the class of their default controller by defining defaultControllerClass, which returns the class from which defaultController creates instances. So defaultControllerClass is the real factory method, that is, the method that subclasses should override.
  2. In Smalltalk-80 the factory method parserClass defined by Behavior (a superclass of all objects representing classes). This enables a class to use a customized parser for its source code.
  3. The Orbix ORB system from IONA Technologies uses Factory Method to generate an appropriate type of proxy when an object requests a reference to a remote object.

 

Related Patterns:

  • Abstract Factory is often implemented with factory methods.
  • Factory methods are usually called within Template Methods. In the Document example above, NewDocument() is a template method.
  • Prototypes don’t require subclassing Creator. Instead, they often require an Initialize operation on the product class. Factory Method doesn’t require such operation.

 

Example Factory Method classes in java API:

java.util.Calendar

java.util.ResourceBundle

java.text.NumberFormat

java.nio.charset.Charset

java.net.URLStreamHandlerFactory

 

Non-software example:

The Factory Method defines an interface for creating objects, but lets subclasses decide which classes to instantiate. Injection molding presses demonstrate this pattern. Manufacturers of plastic toys process plastic molding powder, and inject the plastic into molds of the desired shapes. The class of toy (car, action figure, etc.) is determined by the mold.

factory method pattern non software example

Suryateja Pericherla

Suryateja Pericherla

Hello, I am Suryateja Pericherla working as an Asst. Professor in CSE department at Vishnu Institute of Technology. I write articles to share my knowledge and make people knowledgeable regarding certain topics.
Suryateja Pericherla

Latest posts by Suryateja Pericherla (see all)

Related Links:

Note: Do you have a question on this article or have a suggestion to make this article better? You can ask or suggest us by filling in the below form. After commenting, your comment will be held for moderation and will be published in 24-48 hrs.
Scroll Up