Factory Design Pattern

  • Facebook
  • Google
  • LinkedIn
  • Twitter

Factory Pattern is one of the Creational Design Pattern which is used in JDK, spring and struts framework also. You must consider to this design where the objects creation and relationships are loosely coupled. Loose coupling is one of the most important features in software design, which helps in extending new functions in the software without doing any changes to the existing system. In this design you need to define an interface or abstract class for creating an object but subclasses will decide which class to instantiate at run time, means subclasses are responsible to create the instance of the class.

Factory design pattern diagram:

factory design pattern uml

Factory design pattern Example:

We will create Fruit interface which is implemented by all fruit related classes Apple and Banana. All fruit related classes implement getPrice() method. In the FruitFactory class we will create a fruit type of instance and this factory class will decide which fruit related class needs to be instantiated. Here is the code.

Step 1: Create interface Fruit.java and define the getPrice() method
package com.javatutsworld.designpattern;

public interface Fruit {
	int getPrice();
}
Step 2: Create class Apple.java which implement the method of Fruit interface
package com.javatutsworld.designpattern;

public class Apple implements Fruit {

	@Override
	public int getPrice() {
		return 180;
	}
}
Step 3: Create class Banana.java which implement the method of Fruit interface
package com.javatutsworld.designpattern;

public class Banana implements Fruit {

	@Override
	public int getPrice() {
		return 60;
	}
}
Step 4: Create factory class FruitFactory.java which is responsible to create the instance of the class.

package com.javatutsworld.designpattern;

public class FruitFactory {
	public Fruit getFruit(String type) {
		if (type == null) {
			return null;
		}
		if (type.equalsIgnoreCase("Apple")) {
			return new Apple();

		} else if (type.equalsIgnoreCase("Banana")) {
			return new Banana();
		} 
		return null;
	}
}
Step 5: Create main class FruitFactoryImpl.java

package com.javatutsworld.designpattern;

public class FruitFactoryImpl {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		FruitFactory objFruit = new FruitFactory();

		Fruit appFruit = objFruit.getFruit("Apple");
		System.out.println(appFruit.getPrice());

		Fruit banaFruit = objFruit.getFruit("Banana");
		System.out.println(banaFruit.getPrice());
	}
}
Output

Apple Price: 180
Banana Price: 60
Here are some methods which uses Factory Design Pattern in JDK
  • java.util.Calendar#getInstance()
  • java.util.ResourceBundle#getBundle()
  • java.text.NumberFormat#getInstance()
For more details please see
Head First Design Patterns
      Advertisements