Factory design pattern in java

What is the most usual method of creating an instance of a class in java? Most people will answer this question: “using new keyword“. Well, it is considered old fashioned now.  Lets see how??

If object creation code is spread in whole application, and if you need to change the process of object creation then you need to go in each and every place to make necessary changes. After finishing this article, while writing your application, consider using factory pattern.

In my previous post, “Singleton design pattern in java“, we discussed various ways to create an instance of a class such that there can not exist another instance of same class in same JVM.

In this post, i will demonstrate another creational pattern, i.e. Factory pattern, for creating instances for your classes. Factory, as name suggest, is a place to create some different products which are somehow similar in features yet divided in categories.

In java also, factory pattern is used to create instances of different classes of same type.

Sections in this post

  • Background information
  • Implementation
  • Advantages of factory pattern
  • Final notes

Background information

This pattern introduces loose coupling between classes which is the most important principle one should consider and apply while designing the application architecture. Loose coupling can be introduced in application architecture by programming against abstract entities rather than concrete implementations. This not only makes our architecture more flexible but also less fragile.

A picture is worth thousand words. Lets see how a factory implementation will look like.

Above class diagram depicts a common scenario using example of car factory which is able to build 3 types of cars i.e. small, sedan and luxury. Building a car requires many steps from allocating accessories to final makeup. These steps can be written in programming as methods and should be called while creating an instance of a specific car type.

If we are unfortunate then we will create instances of car types (e.g. SmallCar) in our application classes and thus we will expose the car building logic to outside world and this is certainly not good. It also prevents us in making changes to car making process because code in not centralized, and making changes in all composing classes seems not feasible.


So far we have seen the classes need to be designed for making a CarFactory. Lets hit the keyboard now and start composing our classes.

CarType.java will hold the types of car and will provide car types to all other classes

package designPatterns.creational.factory;

public enum CarType {

Car.java is parent class of all car instances and it will also contain the common logic applicable in car making of all types.

package designPatterns.creational.factory;

public abstract class Car {

	public Car(CarType model) {
		this.model = model;

	private void arrangeParts() {
		// Do one time processing here

	// Do subclass level processing in this method
	protected abstract void construct();

	private CarType model = null;

	public CarType getModel() {
		return model;

	public void setModel(CarType model) {
		this.model = model;

LuxuryCar.java is concrete implementation of car type LUXURY

package designPatterns.creational.factory;

public class LuxuryCar extends Car {

	LuxuryCar() {

	protected void construct() {
		System.out.println("Building luxury car");
		// add accessories

SmallCar.java is concrete implementation of car type SMALL

package designPatterns.creational.factory;

public class SmallCar extends Car {

	SmallCar() {

	protected void construct() {
		System.out.println("Building small car");
		// add accessories

SedanCar.java is concrete implementation of car type SEDAN

package designPatterns.creational.factory;

public class SedanCar extends Car {

	SedanCar() {

	protected void construct() {
		System.out.println("Building sedan car");
		// add accessories

CarFactory.java is our main class implemented using factory pattern. It instantiates a car instance only after determining its type.

package designPatterns.creational.factory;

public class CarFactory {
	public static Car buildCar(CarType model) {
		Car car = null;
		switch (model) {
		case SMALL:
			car = new SmallCar();

		case SEDAN:
			car = new SedanCar();

		case LUXURY:
			car = new LuxuryCar();

			// throw some exception
		return car;

In TestFactoryPattern.java, we will test our factory code. Lets run this class.

package designPatterns.creational.factory;

public class TestFactoryPattern {
	public static void main(String[] args) {


Building small car
Building sedan car
Building luxury car

As you can see, factory is able to return any type of car instance it is requested for. It will help us in making any kind of changes in car making process without even touching the composing classes i.e. classes using CarFactory.

Advantages of factory pattern

By now, you should be able to count the main advantages of using factory pattern. Lets note down:

  • The creation of an object precludes its reuse without significant duplication of code.
  • The creation of an object requires access to information or resources that should not be contained within the composing class.
  • The lifetime management of the generated objects must be centralized to ensure a consistent behavior within the application.

Final notes

Final notes

Factory pattern is most suitable where there is some complex object creation steps are involved. To ensure that these steps are centralized and not exposed to composing classes, factory pattern should be used. We can see many examples of factory pattern in JDK itself e.g.

I hope, I have included enough information to make this post informative. If you still have some doubt, please leave a comment. I will be happy to discuss with you.

Happy Learning !!


I have 7 Years of rich experience in java technology. This has only increased my hunger to learn more. In this blog, i will be writing on different topics occasionally, and would love to engage in some meaningful serious discussions with you folks.

You may also like...

35 Responses

  1. Hi in the original GOF factory pattern, there is a concept of having a creator and a concrete creator. I find this missing in your example. The CarFactory class is of course the concrete creator , but it does not extend from an abstract class / interface (creator)

    So is it OK to call it a factory pattern without having the creator / concrete creator

  2. Evaldas says:

    It’s impossible to read this article on Samsung Galaxy 10.1 – the black advert strip jumps to the center of the webpage and covers the article text.

  3. How to reuse the same object? i.e If we call – CarFactory.buildCar(CarType.SMALL) multiple times, it returns a new object for every call.

    Praveen Das

    • Lokesh says:

      Hi Praveen, another question in response to your question. Why would a factory will return the same instance on each request? What’s use of this approach? I believe you will have a good reason for it, so please share with us. It will expand our thought process as well.

      To answer your question, you can apply singleton pattern on different Car objects and return from construct() method.

      On another thought, you should better using prototype pattern, if you want to save some CPU cycles in car construction process. Singleton simply doesn’t make sense to me.


      • Hi Lokesh, I’m looking at implementing a mailbox which fetches messages at a specific time interval.

        Each messages fall under different types of validations, so depending on the NotificationType i call the ValidationFactory.

        since there are for ex:22 notifications, and 100 messages, the notifications can be of same type. in this case i should be able to reuse the already created object for that particular NotificationType.

        NotificationType would be my enum class.

        ValidationService would be the parent class for all validation instances.

        ValidationFactory would get me the respective object for the notificationType as input.


  4. Student says:

    Thanks for this wonderful example. My doubt is why do I get a warning in my IDE that the method “construct()” shouldn’t be called in side the construtor because it’s an overridable method?

    I read that it has something to do with inheritance and if other classes extend this class things COULD go wrong down the line if someone overrides that method in another place.

    Did I understand correctly the potencial danger here?

    • iles says:

      There is a danger in doing this and you should not do it (add overridable methods in the constructor)

      Effective Java 2nd Edition, Item 17: Design and document for inheritance or else prohibit it

      “There are a few more restrictions that a class must obey to allow inheritance. Constructors must not invoke overridable methods, directly or indirectly. If you violate this rule, program failure will result. The superclass constructor runs before the subclass constructor, so the overriding method in the subclass will get invoked before the subclass constructor has run. If the overriding method depends on any initialization performed by the subclass constructor, the method will not behave as expected.”

  5. Thanks Lokesh Gupta ji.

  6. Roman Pereginiak says:

    I guess there is one small mistake (inaccuracy) in your example.
    You have to make method constcut() abstract and put it into constructor instead of method arrangeParts():
    public Car(CarType model) {
    this.model = model;
    //arrangeParts(); // remove this. You cold leave it but it just misslead you, it has nothing to design pattern.
    construct(); // abstrac method! will be called implementation from interited class.
    Then constructor LuxuryCar will look like:
    LuxuryCar() {
    //construct(); // remove this!

  7. Mirek says:

    Good post, thank you. Could you make it a bit more complex (as part2) in the way, lets say: Car is composed of underframe, engine and body and each of this component is created by factory depending of type of a car. What I’d like to see is how those factories will be used together, where to put it, how to call it. Thanks

      • Mirek says:

        Ok, thanks. What I’m trying to achieve is how to junittest class which have nested classes which have nested classes. Lets say: Service class uses nested Util class and Util class uses nested library class. And that library class is created by hardcoded new LibClass() but I’d like to use factory to easily switch instance to LibTestClass(). That is because LibClass connects to the internet but I’d like to mock it. By factory. Not by EasyMock or so even if it is possible. Lets say in another production environment I’d like to use LibClassDatabase() instead of LibClassHttp()

  8. Søren Tryde Andersen says:

    Awesome stuff! Thanks.

  9. srikanth says:

    Read jus now before interview…really worth it!

  10. Roshan says:

    Thank You. That was useful. :)

  11. alupis says:

    This was helpful. Thanks! :)

  12. kushi says:

    You did not mention where CarFactory.buildCar() should be called… You have just written the testing part but I suppose the integration part is missed…

  13. satnam singh says:

    thanks dear

  1. October 23, 2012

    [...] What is the most usual method of creating an instance of a class in java? Most people will answer this question: “using new keyword“. Well, it is considered old fashioned now.  Lets see…  [...]

  2. October 29, 2012

    [...] is yet another creational design pattern and is considered as another layer of abstraction over factory pattern. In this post, i will expand the problem statement discussed in previous post and will see, how [...]

  3. November 12, 2013

    [...] What is the most usual method of creating an instance of a class in java? Most people will answer this question: “using new keyword“. Well, it is considered old fashioned now. Lets see…  [...]

Note:- In comment box, please put your code inside [java] ... [/java] OR [xml] ... [/xml] tags otherwise it may not appear/post as intended.

Want to ask any question? Or suggest anything?