Java design pattern Factory

In this article, we will look at another Java design pattern from the category of patterns designed for creating objects (creational patterns) – Factory.

Read more about design patterns:

What is the Factory design pattern?

The Factory design pattern is a software design pattern whose main goal is to provide a simple and flexible way to create class instances without having to directly specify specific classes in client code.

What problem does the Factory design pattern solve?

If we have classes that implement or are derived from a common interface, we want to be able to create instances of those classes without having to directly mention a specific class. This is useful if we don’t want the client code to be bound to a specific implementation, but want to retrieve an object based on some parameter or condition.

Example of Factory implementation in Java

Now we will show how to implement the Factory pattern in Java. This example illustrates how the Factory pattern allows you to create different types of objects (chocolates) using a single factory class without having to directly specify specific classes in client code.

Chocolate.java

In this example, we have created an abstract class Chocolate to represent chocolate.

package designpatterns;

// Abstract class representing chocolate
public abstract class Chocolate {
    public abstract void taste();
}

Milka.java, Lindt.java

We then implemented two concrete classes, Milka and Lindt, which extend the abstract class Chocolate. Each of these classes defines its own implementation of the ochutnat() method.

package designpatterns;

// Concrete implementation of Lindt brand chocolate
public class Lindt extends Chocolate {
    @Override
    public void taste() {
        System.out.println("Lindt: Velvety and luxurious taste");
    }
}

// Concrete implementation of Milka brand chocolate
public class Milka extends Chocolate {
    @Override
    public void taste() {
        System.out.println("Milka: Sweet and milky taste");
    }
}

ChocolateFactory.java

Next, we created the ChocolateFactory class, which is used to create instances of chocolate based on the brand. The makeChocolate(String znacka) method creates a chocolate according to the given parameter znacka (= brand). If the brand is Milka, an instance of the Milka class is created, if the brand is Lindt, an instance of the Lindt class is created. If an unknown tag is specified, an IllegalArgumentException is thrown.

package designpatterns;

// Factory class for chocolate production
public class ChocolateFactory {
    public Chocolate makeChocolate(String brand) {
        if(brand.equalsIgnoreCase("Milka")) {
            return new Milka();
        }
        else if(brand.equalsIgnoreCase("Lindt")) {
            return new Lindt();
        }
        else {
            throw new IllegalArgumentException("Unknown chocolate brand: " + brand);
        }
    }
}

Main.java

We created an instance of ChocolateFactory in the client code, and used it to create and taste Milka and Lindt chocolate.

import designpatterns.*;

// Example
public class Main {
    public static void main(String[] args) {
        ChocolateFactory factory = new ChocolateFactory();

        // Making and tasting of Milka brand chocolate
        Chocolate milka = factory.makeChocolate("Milka");
        milka.taste();

        // Making and tasting of Lindt brand chocolate
        Chocolate lindt = factory.makeChocolate("Lindt");
        lindt.taste();
    }
}

Output of the program

factory design pattern program output
output of the example Factory

We have prepared the files with the above mentioned Java Factory example in the form of code that you can run directly in Java. Download the code here.

If you’re a Java developer looking for a job, read more about developer salary and check out our latest job offers.

About the author

Jozef Wagner

Java Developer Senior

Viac ako 10 rokov programujem v Jave, momentálne pracujem v msg life Slovakia ako Java programátor senior a pomáham zákazníkom implementovať ich požiadavky do poistného softvéru Life Factory. Vo voľnom čase si rád oddýchnem v lese, prípadne si zahrám nejakú dobrú počítačovú hru.

Let us know about you