We are going to look at making objects than just using the new operator.  Factory Method Pattern in Java can help you save from embarrassing dependencies.

Factory Method Pattern

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

Factory Method Pattern in Java

Let’s jump into implementing Factory Method Pattern in Java,

High Level Steps for Implementation

  1. Create abstract Product class
  2. Create Concrete Product subclasses
  3. Create abstract Creator class
  4. Create Concrete Creator subclasses

Step 1: Create abstract Product class

We will start with abstract Mobile class and all the concrete Mobile’s will derive from below class. Below abstract class provide some basic methods in process of creating Mobile.

public abstract class Mobile {

  String name;

  String processor;
  String ram;
  String camera;
  String mobileCase;
  
  void prepare() {
    System.out.println("Purchasing "+processor);
    System.out.println("Purchasing "+ram);
    System.out.println("Purchasing "+camera);
    System.out.println("Purchasing "+mobileCase);
  }

  void assemble() {
    System.out.println("Assemble every parts");
  }

  void verify() {
    System.out.println("Verify mobile functions");
  }

  void boxIt() {
    System.out.println("Box it in respective Mobile box");
  }

  String getName() {
    return name;
  }
}

Step 2: Create Concrete Product subclasses

We will implement some concrete subclasses as below,

public class OnePlusIndia extends Mobile{

  public OnePlusIndia() {
    name = "OnePlus from India";
    processor = "Indian Standard Processor";
    camera = "Indian Standard Camera";
    ram = "Indian Standard RAM";
    mobileCase = "Indian Standard Mobile Case";
  }
}
public class SamSungUSA extends Mobile {

  public SamSungUSA() {
    name = "SamSung from USA";
    processor = "USA Standard Processor";
    camera = "USA Standard Camera";
    ram = "USA Standard RAM";
    mobileCase = "USA Standard Mobile Case";
  }
}

Like above classes, implement SamSungIndia, OnePlusUSA and so on…

Step 3: Create abstract Creator class

Declaring a Factory Method

public abstract class MobileStore {

        // All the responsibilty for instantiating Mobiles has been moved into a method that acts as a factory
  protected abstract Mobile createMobile(String type);

        // The subclasses of MobileStore handle object instantiation for us in the createMobile() method.
  public Mobile orderMobile(String type) {
    Mobile mobile = createMobile(type);
    mobile.prepare();
    mobile.assemble();
    mobile.verify();
    mobile.boxIt();
    return mobile;
  }
}

abstract Product factoryMethod(String type)

  1. A factory method is abstract so the subclasses are counted on to handle object creation
  2. A factory method returns a Product that is typically used within methods defined in superclass
  3. A factory method isolates the client from knowing what kind of concrete product is actually created
  4. A factory method may be parameterized (or not) to select among several variations of the product

Step 4: Create Concrete Creator subclasses

Let’s create some concrete classes for MobileStore,

public class IndiaStore extends MobileStore{

  @Override
  protected Mobile createMobile(String type) {
    if(type.equals("oneplus")) {
      return new OnePlusIndia();
    }
    else if(type.equals("samsung")) {
      return new SamSungIndia();
    }
    return null;
  }

}
public class USAMobileStore extends MobileStore{

  @Override
  protected Mobile createMobile(String type) {
    if(type.equals("oneplus")) {
      return new OnePlusUSA();
    }
    else if(type.equals("samsung")) {
      return new SamSungUSA();
    }
    return null;
  }
}

Step 5:

Time for ordering Mobile !!!

public class MobileTestDrive {

  public static void main(String[] args) {

                // Creating two different Stores
    MobileStore indMobileStore = new IndiaStore();
    MobileStore usaMobileStore = new USAMobileStore();
    
                // Use each store to orderMobile
    Mobile mobile = indMobileStore.orderMobile("oneplus");
    System.out.println("Mobile created as "+mobile.getName());
    
    System.out.println("\n");
    
    mobile = usaMobileStore.orderMobile("samsung");
    System.out.println("Mobile created as "+mobile.getName());
  }
}

Output

Purchasing Indian Standard Processor
Purchasing Indian Standard RAM
Purchasing Indian Standard Camera
Purchasing Indian Standard Mobile Case
Assemble every parts
Verify mobile functions
Box it in respective Mobile box
Mobile created as OnePlus from India


Purchasing USA Standard Processor
Purchasing USA Standard RAM
Purchasing USA Standard Camera
Purchasing USA Standard Mobile Case
Assemble every parts
Verify mobile functions
Box it in respective Mobile box
Mobile created as SamSung from USA

Points for Better Understanding about Factory Method Pattern

Product Class

All products must implement the same interface so that the classes that use the products can refer to the interface, not the concrete class.

Creator Class

The Creator is a class that contains the implementations for all of the methods to manipulate products, except for the factory methods

The abstract factory method is what all Creator subclasses must implement

Concrete Creator / Concrete Product

The Concrete Creator implements the factoryMethod() which is the method that actually produces products

The Concrete Creator is responsible for creating one or more concrete products. It is the only class that has the knowledge of how to create these products.

Conclusion

Factory method lets subclasses decide which class to instantiate. They say “decide” not because the pattern allows subclasses themselves to decide at runtime, but because the creator class is written without knowledge of the actual products that will be created, which is purely by the choice of the subclass that is used.

 

Please follow and like us:
error