About 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.

Solve design problems using Factory Pattern

Factory design pattern is one of the most commonly used patterns in object oriented environment. It is again from the Creational Design pattern category i.e. all about object creation.

There are certain cases where the object creation is complex and might require some level of abstraction so that the client code is unaware of these complexities and internal implementation details. There might be scenarios where object creation is scattered and repetitive in various parts of the code.The Factory pattern resolves these issues by defining an interface which specifically creates the object but gives the flexibility to the implementation classes to decide on which class to instantiate.

Definition:
The Factory method pattern is to define an interface for creating objects but delegates the object creation to the subclasses.

Objective:
Looking at the problem statement the objective should be:

  • Client should be unaware of the object instantiation
  • Client should access the objects through a common interface.
Do you know?
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.

Which principle of Object Oriented Design is used in Factory pattern?

Encapsulation : because it encapsulates the creation code from the client. And obviously you can then think that the benefits of encapsulation are also applicable for this pattern like loose coupling and cohesion.

Practical Example:

Consider a Garment Factory which produces various types of garments like shirt, trousers. The consumers can request for the required types of garments through the factory. However from consumer’s perspective they are completely unaware of who is creating this object. They just know that the Factory is providing them the required garments.

Problem Statement:

It is a standard practice that objects are created by calling the “new” keyword. Imagine a scenario that there are multiple cases in the client class and we call multiple new keywords for creating new objects.

if (selection.equalsIgnoreCase("Trouser")) {
   return new Trouser();
  } else if (selection.equalsIgnoreCase("Shirt")) {
   return new Shirt();
  }

If we now have to add jacket or sweater we have to keep on modifying the client code and further add the new keyword. This creates a dependency on the client code and in turn makes it difficult to maintain.

Another problem is that the client application has to know how many types of concrete classes are available upfront. Later if we have to add another concrete class e.g. sweater or jacket then client code has to be changed and recompiled.

Solution:
To resolve above problems factory pattern can be used explicitly.

  • The first problem of accessing too many new keyword can be resolved by using a Factory class.
  • The second problem can be solved by using an interface which the concrete classes will implement and the client will always point to the interface class rather than the concrete classes. So in this way client will be completely unaware of various types of concrete classes which will be required.
What is an interface?
An Interfacein Java is a collection of method definitions without implementation. The class which implements the interface has to provides the implementation and must implement all the methods described in the interface. The interface is a contract which tells the classes what to be done leaves it for the classes to decide on how they can be implemented.

interface Bounceable {
      void setBounce();
}

The below class diagram will give a complete overview of implementation of Factory Pattern:

Factory Pattern Class Diagram

Let’s take a look at the sample code to implement the Factory Pattern:

GarmentType.java
public interface GarmentType {
 String print();
}
Trouser.java
public class Trouser implements GarmentType {
 @Override
 public String print() {
  System.out.println("Trouser Created");
  return "Trouser";
 }

}
Shirt.java
public class Shirt implements GarmentType {
 @Override
 public String print() {
  System.out.println("Shirt Created");
  return "Shirt";
 }
}
GarmentFactory.java
public class GarmentFactory {
 public static 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");
 }
}
Client.java
public class Client {
 public static void main(String[] args) {
  System.out.println("Enter your selection:");
  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  String selection = null;
  try {
   selection = br.readLine();
  } catch (IOException e) {
   e.printStackTrace();
  }
  GarmentType objGarmentType = GarmentFactory.createGarments(selection);
  System.out.println(objGarmentType.print());
 }
}

Advantage of Factory Pattern:

a)This client does not need to know about the subclass of objects which requires to be created. It requires the reference to the interface and the factory object.
b)The object creation processes are taken away from the client to the factory and thereby decoupling the client code with the object creation code. This in turn will help in reusability as this code can be used by other clients.
c)The Factory pattern also helps in the scalability of the application as the client code only refers to the interface and we can add more products implementing the interface without making many changes in the client code.
d)Code maintainability is a beneficial if the application uses Factory pattern as the object creation is centralized.

Reference: Solve design problems using Factory Pattern from our JCG partner Mainak Goswami at the Idiotechie blog.

Related Whitepaper:

Bulletproof Java Code: A Practical Strategy for Developing Functional, Reliable, and Secure Java Code

Use Java? If you do, you know that Java software can be used to drive application logic of Web services or Web applications. Perhaps you use it for desktop applications? Or, embedded devices? Whatever your use of Java code, functional errors are the enemy!

To combat this enemy, your team might already perform functional testing. Even so, you're taking significant risks if you have not yet implemented a comprehensive team-wide quality management strategy. Such a strategy alleviates reliability, security, and performance problems to ensure that your code is free of functionality errors.Read this article to learn about this simple four-step strategy that is proven to make Java code more reliable, more secure, and easier to maintain.

Get it Now!  

Leave a Reply


seven − 3 =



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books