Define an interface or abstract class for creating an object but let the Sub class decide which class to instantiate.

Required

  1. Interface under which the object can be mocked
  2. Different class that should instantiated using Interface Reference
  3. Class with main() method which starts the whole process

Interface
AccountFactory.java

package com.mugil.factory;
public interface AccountFactory 
{	
  void calculateInterest();
}

Different classes
CurrentAccount.java

public class CurrentAccount implements AccountFactory 
{
  @Override
  public void calculateInterest() 
  {
    System.out.println("Interest Calculation for Current Account");
  }
}

RecurringDepositAccount.java

public class RecurringDepositAccount implements AccountFactory 
{
  @Override
  public void calculateInterest() 
  {
    System.out.println("Interest Calculation for Recurring Deposit");
  }
}

SavingsAccount.java

public class SavingsAccount implements AccountFactory 
{
  @Override
  public void calculateInterest() 
  {
    System.out.println("Interest Calculation for Savings Account");
  }
}

Class with main() method
CalculateInterest.java

public class CalculateInterest 
{	
  public static void main(String[] args) 
  {	
    //Received at Runtime
    String accountType = "SAV";
		
    AccountFactory objAccountFactory =  null;
		
    if(accountType.equals("SAV"))
    {
	objAccountFactory = new SavingsAccount();
    }
    else if(accountType.equals("REC"))
    {
	objAccountFactory = new RecurringDepositAccount();
    }
    else if(accountType.equals("CUR"))
    {
	objAccountFactory = new CurrentAccount();
    }
		
	objAccountFactory.calculateInterest();
   }
}

When to use factory methods?

Comments are closed.