Factory Method Design Pattern Java

Profile picture for user arilio666

The Factory Method is a popular design pattern used in object-oriented programming that provides an interface for creating objects in a superclass and allows subclasses to modify the type of objects that will be made. 

This pattern is proper when you want to decouple the creation of objects from their usage. This creational pattern is one of the best ways to create an object.

Let us create OS, Android, and ios, where the OS class is an interface with only a method, and the other two implement OS and overrides.

OS Class:

package fac;
public interface OS {
    void spec();
}
  • We will access this spec by overriding it in another class after implementing it.

Android Class:

package fac;
public class Android implements OS {
    @Override
    public void spec() {
        System.out.println("New Jellybean Is Out");
    }
}

Ios Class:

package fac;
public class Ios implements OS {
    @Override
    public void spec() {
        System.out.println("IOS 17 Incoming");
    }
}

MainFactoryOS Class:

  • We created this class to write a simple if else statement for both the Android and ios classes to access the contents based on a string.
package fac;
public class MainFactoryOS {
    public OS getInstance(String str) {
        if (str.equals("IOS 17")) {
            return new Ios();
        } else
            return new Android();
    }
}
  • We can see here that instead of creating an object every time, we can access it using the string we pass.

FactoryMain Class:

package fac;
public class FactoryMain {
    public static void main(String[] args) {
        MainFactoryOS mfo = new MainFactoryOS();
        OS instance = mfo.getInstance("IOS 17");
        instance.spec();
    }
}
  • In this class, we will create the object of the MainFactoryOS class and access the getInstance method by passing the string. This will trigger the required class based on the string we pass.
Tags