Design patterns Java Software Engineering

Factory Method pattern

Introduction

The Factory Method pattern is one the most used design patterns. It is creational type of design pattern, so it is one of the best ways to create objects in any programming language. We will implement this pattern in Java.

The Factory Method Pattern allows you to create objects without specifying the exact class of object that will be created.

Definition and structure

Before we introduce Factory design pattern, let’s take a look at official definition of the pattern by GOF:

The Factory Method Pattern defines an interface for creating an object, but let’s subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclass.

Implementation

Step 1

First we need to create an abstract interface (not Java interface) and that abstract interface can be abstract class or Java interface. We are going to use abstract class, but you can use Java interface if you want it and if it’s design fits more in your project.

public abstract class Car {
    abstract void drive();
}

Step 2

Since we create an abstract class, now we need to create all concrete classes that will extend our abstract class Car. I am going to create just 3 simple classes called BMW, Audi and Toyota.

public class Audi extends Car{
    @Override
    void drive() {
        System.out.println("I am driving Audi car");
    }    
}
public class BMW  extends Car{
    @Override
    void drive() {
        System.out.println("I am driving BMW car");
    }    
}
public class Toyota extends Car{
    @Override
    void drive() {
        System.out.println("I am driving Toyota car");
    }    
}

Step 3

Now we need to create factory class, that will contain that factory method that will hide concreate implementation from the client. I am going to create class CarFactory.

public class CarFactory {    
    public static Car create(String carName){
        if(carName == null){
            return null;
        }
        if(carName.equals("BMW")){
            return new BMW();
        }
         if(carName.equals("Audi")){
            return new Audi();
        }
          if(carName.equals("Toyota")){
            return new Toyota();
        }
        return null;
    }    
}

Step 4

We are almost done, but we still need to create main Java class where we will execute our code.

public class FactoryMethodPattern {
    public static void main(String[] args) {        
        Car car1 = CarFactory.create("BMW");
        Car car2 = CarFactory.create("Audi");
        Car car3 = CarFactory.create("Toyota");
        
        car1.drive();
        car2.drive();
        car3.drive();        
    }    
}

Step 5

That’s all, now we can run the app and you should get this output:

I am driving BMW car
I am driving Audi car
I am driving Toyota car

 

You Might Also Like

No Comments

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.