DEV Community

Ashutosh Dubey
Ashutosh Dubey

Posted on

Java Factory Pattern with example Explained

Introduction

The factory pattern is a creational design pattern in Java that provides an interface for creating objects in a super class, but allows subclasses to alter the type of objects that will be created.

One of the main benefits of using the factory pattern is that it allows for the creation of objects without the client specifying the exact class of object that will be created. This is useful when the client does not need to know the implementation details of the objects being created, or when there is the possibility of adding new types of objects in the future.

To implement the factory pattern in Java, you need to create a factory interface and concrete classes that implement the interface. The factory interface should have a method for creating objects, which will be implemented by the concrete classes.

Example

For example, consider a simple application that allows users to create and customize their own cars. The application has three types of cars: sedan, hatchback, and SUV. We can implement the factory pattern by creating a CarFactory interface with a createCar() method, and concrete classes SedanFactory, HatchbackFactory, and SUVFactory that implement the CarFactory interface and create specific types of cars.

public interface CarFactory {
    public Car createCar();
}

public class SedanFactory implements CarFactory {
    public Car createCar() {
        return new Sedan();
    }
}

public class HatchbackFactory implements CarFactory {
    public Car createCar() {
        return new Hatchback();
    }
}

public class SUVFactory implements CarFactory {
    public Car createCar() {
        return new SUV();
    }
}
Enter fullscreen mode Exit fullscreen mode

To use the factory pattern, the client can simply create an instance of the appropriate factory and call the createCar() method to create a new car. For example:

CarFactory factory = new SedanFactory();
Car car = factory.createCar();
Enter fullscreen mode Exit fullscreen mode

This allows the client to create a sedan without having to specify the exact class of the object that will be created. If the application needs to support additional types of cars in the future, all that is required is to create a new factory class that implements the CarFactory interface.

Conclusion

The factory pattern is a useful way to create objects in a flexible and extensible manner, and is particularly useful when the exact type of object to be created is not known at compile-time. It can also help to reduce the coupling between the client and the implementation classes of the objects being created.

Top comments (0)