Core Java

Design Best practices using Factory Method Pattern

In the previous Design Pattern example we have explained about a flavor of Factory pattern which is commonly used nowadays. In this session we will understand a more advanced solution which had more abstraction. This pattern is called Factory Method design pattern.

Definition:
The Factory method pattern exposes a method for creating objects but delegates the object creation to the subclasses. Factory method design pattern resolves these problems in similar lines to the Factory pattern with an additional level of abstraction.

The object can be instantiated using the new keyword. e.g. Object A creates another object B using:

ClassB objB = new ClassB();

So object A holds a reference to object B.

Object instantiation Object instantiation

Since Object A is now dependent on Object B if the later gets modified then we will have to recompile the Object A. Well life is not that easy. The object creation can be more complex and if there is more coupling then the maintenance will be a painful and expensive job in software development.

To avoid such worst case situations the creational design patterns comes for rescue. They try to create loose coupling between the client and the object creator and gives several other design benefits for the developers. Factory Method pattern is one such pattern to solve the design issues.

Common use:
Factory method design pattern is commonly used in various frameworks such as Struts, Spring, Apache in conjunction with decorator design pattern. There are various J2EE patterns which are based on this Factory pattern e.g. DAO pattern.

Let’s take the same example of Garment Factory where we were creating various types of Garments but the client was completely unaware of how these products are created. Even if we had to add a new Garment Type like Jacket the client code need not be changed and thus increases the flexibility of the application.

Factory Pattern Class Diagram

When to use Factory Method Pattern?

  • The creation of object requires reuse of the code without significant duplication of code.
  • A class will not know what subclasses will be required to create.
  • Subclasses may specify what objects should be created.
  • Parent classes will delegate the creation of objects to its subclasses.

Structure

The below diagram highlights a typical structure of the Factory Method Design pattern. Unlike the above example there is an additional Factory Abstract (Factory) class has been added.

Factory Method Design Pattern(UML)

In the above diagram following are the participants:

  • Product: This defines an interface for the objects the factory methods creates.
  • Concrete Products: implements the Product interface.
  • Factory (Creator): This is an abstract class which defines the Factory Method which returns a product object.
  • Concrete Factory: This class implements and overrides the methods which were declared by the parent Factory class.

The client(e.g. object Class A) will wants to use the products which are created by the ConcreteFactory class (object Class B). However in this case the client only holds a reference to Interface B rather than the object ‘Class B’ and so it doesn’t need to know anything about classB. In fact there can be multiple class which can implement the abstract class.

What is meant by Factory Method pattern allows the subclasses to decide which class to instantiate?
It basically means that the Factory abstract class is coded without knowing what actual ConcreteProduct classes will be instantiated i.e. whether it is Trouser or whether it is Shirt. This is completely determined by the ConcreteFactory class.

Now let’s implement the above pattern to our GarmentFactory example.

Factory Method Example

Let’s do some hands on now. We are not repeating the code for Concrete Products like Shirt.java and Trouser.java which can be found in the Factory Pattern article.

A new Factory abstract class has been created which is client facing.

public abstract class Factory {
 protected abstract GarmentType createGarments(String selection);
 }

GarmentFactory class needs to be modified to inherit the abstract class Factory.

public class GarmentFactory extends Factory{
	public GarmentType createGarments(String selection) {
		if (selection.equalsIgnoreCase('Trouser')) {
			return new Trouser();
		} else if (selection.equalsIgnoreCase('Shirt')) {
			return new Shirt();
		}
		throw new IllegalArgumentException('Selection doesnot exist');
	}
}

The client class refers to the Factory class and class the createGarments(selection) method of the Factory to create the product at runtime.

Factory factory = new GarmentFactory();
GarmentType objGarmentType = factory.createGarments(selection);
System.out.println(objGarmentType.print());

 
Benefits:

  • Code is flexible, loosely coupled and reusable by moving the object creation from the client code to the Factory class and it’s subclasses. It is easier to maintain such code since the objection creation is centralized.
  • The client code deals with only the Product interface and hence any Concrete Products can be added without modifying the client code logic.
  • The advantage of a Factory Method is that it can return the same instance multiple times, or can return a subclass rather than an object of that exact type.
  • It encourages a consistency in the code as object is created through a Factory which forces a definite set of rules which everybody must follow. This avoids using different constructor at different client.

 
Example:

JDBC is a good example for this pattern; application code doesn’t need to know what database it will be used with, so it doesn’t know what database-specific driver classes it should use. Instead, it uses factory methods to get Connections, Statements, and other objects to work with. This gives flexibility to change the back-end database without changing your DAO layer.
Below are some examples from the SDK:
valueOf() method which returns object created by factory equivalent to value of parameter passed.
getInstance() method which creates instance of Singleton class.
newInstance() method which is used to create and return new instance from factory method every time called.
Download Sample Code
 

Reference: Design Best practices using Factory Method Pattern from our JCG partner Mainak Goswami at the Idiotechie blog.

Mainak Goswami

Mainak Goswami is an experienced Technology Consultant specializing in JEE, Web Development and Open source technologies. He is currently based out of United Kingdom. He is a technology enthusiast trying to explore the latest in the world of technology. His current area of interest is Mobility, NoSQL and Cloud computing. In past time he loves blogging on his website Idiotechie.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button