Factory Method Design Pattern Java

By | | Updated : 2021-10-02 | Viewed : 32 times

Factory Method Design Pattern Java

One of the creational design patterns is for creating an object based on the class name.

Factory Method Design Pattern Java

First, we will look at what is Factory Method Design Pattern in Java. It is one of the creational design patterns. You might be aware of creational design patterns. Actually, these are used for creating objects. Factory method design pattern also simply creates objects based on the name of the class.

Factory Method Design Pattern Example

Now we will look at the example of CakeFactory. Here it provides different types of Cake objects based on the Cake's name.

Cake .java
public interface Cake {
    Long getCakePrice();
}
BlackForest.java
public class BlackForest implements Cake {

    public Long price;

    public BlackForest(Long price) {
        this.price = price;
    }

    @Override
    public Long getCakePrice() {
        return price;
    }
}
ChocolateTruffle.java
public class ChocolateTruffle implements Cake {

    public Long price;

    public ChocolateTruffle(Long price) {
        this.price = price;
    }

    @Override
    public Long getCakePrice() {
        return price;
    }
}
StrawBerryCrush.java
public class StrawBerryCrush implements Cake {
    public Long price;

    public StrawBerryCrush(Long price) {
        this.price = price;
    }

    @Override
    public Long getCakePrice() {
        return price;
    }
}

We create all the Cake and its subclasses. So now we will write the CakeFactory in which the logic exists for the creation of different types of Cakes.

CakeFactory.java
public class CakeFactory {
    public Cake makeCake (String cakeName) {
        Cake cake = null;
        if (cakeName.equalsIgnoreCase("BlackForest")) {
            cake = new BlackForest(600l);
            System.out.println("Ordered cake is: BlackForest and price is:" + cake.getCakePrice() + "$");
        } else if (cakeName.equalsIgnoreCase("StrawBerryCrush")) {
            cake = new StrawBerryCrush(500l);
            System.out.println("Ordered cake is: StrawBerryCrush and price is:" + cake.getCakePrice() + "$");
        } else if (cakeName.equalsIgnoreCase("ChocolateTruffle")) {
            cake = new ChocolateTruffle(650l);
            System.out.println("Ordered cake is: ChocolateTruffle and price is:" + cake.getCakePrice() + "$");
        } else {
            System.out.println("The order cake is not presented now.");
        }
        return cake;
    }
}

When we order Cake then it will be ordered with a price. Notice the below-given code snippet for ordering the Cake.

OrderCake.java
public class OrderCake {
    public static void main(String[] args) {
        CakeFactory factory = new CakeFactory();
        factory.makeCake("StrawBerryCrush");
    }
}

To refer GitHub repo please look at Java-Factory-Method-Design-Pattern

Leave A Reply