Abstract Factory Pattern

Abstract Factory Pattern

Abstract Factory Pattern says that just define an interface or abstract class for creating families of related (or dependent) objects but without specifying their concrete sub-classes. Abstract Factory patterns work around a super-factory which creates other factories. This factory is also called as factory of factories. 
An Abstract Factory Pattern is also known as Kit.

Advantage of Abstract Factory Pattern

  • Abstract Factory Pattern isolates the client code from concrete (implementation) classes.
  • It eases the exchanging of object families.
  • It promotes consistency among objects.

Usage of Abstract Factory Pattern

  • When the system needs to be independent of how its object are created, composed, and represented.
  • When the family of related objects has to be used together, then this constraint needs to be enforced.
  • When you want to provide a library of objects that does not show implementations and only reveals interfaces.
  • When the system needs to be configured with one of a multiple family of objects.

UML for Abstract Factory Pattern

  • We are going to create a Bank interface and a Loan abstract class as well as their sub-classes.
  • Then we will create AbstractFactory class as next step.
  • Then after we will create concrete classes, BankFactory, and LoanFactory that will extends AbstractFactory class
  • After that, AbstractFactoryPatternExample class uses the FactoryCreator to get an object of AbstractFactory class.
  • See the diagram carefully which is given below:
abstract factory pattern 

Example of Abstract Factory Pattern

Here, we are calculating the loan payment for different banks like HDFC, ICICI, SBI etc.
Step 1: Create a Bank interface
  1. import java.io.*;     
  2. interface Bank{  
  3.         String getBankName();  
  4. }  
Step 2: Create concrete classes that implement the Bank interface.
  1. class HDFC implements Bank{  
  2.          private final String BNAME;  
  3.          public HDFC(){  
  4.                 BNAME="HDFC BANK";  
  5.         }  
  6.         public String getBankName() {  
  7.                   return BNAME;  
  8.         }  
  9. }  
  1. class ICICI implements Bank{  
  2.        private final String BNAME;  
  3.        ICICI(){  
  4.                 BNAME="ICICI BANK";  
  5.         }  
  6.         public String getBankName() {  
  7.                   return BNAME;  
  8.        }  
  9. }  
  1. class SBI implements Bank{  
  2.       private final String BNAME;  
  3.       public SBI(){  
  4.                 BNAME="SBI BANK";  
  5.         }  
  6.        public String getBankName(){  
  7.                   return BNAME;  
  8.        }  
  9. }  
Step 3: Create the Loan abstract class or interface.
  1. public abstract Loan{  
  2.    protected double rate;  
  3.    abstract void getInterestRate(double rate);  
  4.    default void calculateLoanPayment(double loanamount, int years)  {  
  5.         /* 
  6.               to calculate the monthly loan payment i.e. EMI 
  7.               rate=annual interest rate/12*100; 
  8.               n=number of monthly installments;            
  9.               1year=12 months. 
  10.               so, n=years*12
  11.             */  
  12.          double EMI;  
  13.          int n;  
  14.          n=years*12;  
  15.          rate=rate/1200;  
  16.          EMI=((rate*Math.pow((1+rate),n))/((Math.pow((1+rate),n))-1))*loanamount;  
  17.          System.out.println("your monthly EMI is "+ EMI +" for the amount"+loanamount+" you have borrowed");     
  18.  }  
  19. }// end of the Loan abstract class.  
Step 4: Create concrete classes that extend the Loan abstract class..
  1. class HomeLoan implements Loan{  
  2.      public void getInterestRate(double r){  
  3.          rate=r;  
  4.     }  
  5. }//End of the HomeLoan class.  
  1. class BussinessLoan implements Loan{  
  2.     public void getInterestRate(double r){  
  3.           rate=r;  
  4.      }  
  5. }//End of the BusssinessLoan class.  
  1. class EducationLoan extends Loan{  
  2.      public void getInterestRate(double r){  
  3.        rate=r;  
  4.  }  
  5. }//End of the EducationLoan class.  
Step 5: Create an abstract class or interface (i.e AbstractFactory) to get the factories for Bank and Loan Objects.
  1. interface AbstractFactory{  
  2.   default Bank getBank(String bank) [ return null; }  
  3.   default Loan getLoan(String loan) {return null; }
  4. }  
Step 6: Create the factory classes that inherit AbstractFactory class to generate the object of concrete class based on given information.
  1. class BankFactory implements AbstractFactory{  
  2.    public Bank getBank(String bank){  
  3.       if(bank == null){  
  4.          return null;  
  5.       }  
  6.       if(bank.equalsIgnoreCase("HDFC")){  
  7.          return new HDFC();  
  8.       } else if(bank.equalsIgnoreCase("ICICI")){  
  9.          return new ICICI();  
  10.       } else if(bank.equalsIgnoreCase("SBI")){  
  11.          return new SBI();  
  12.       }  
  13.       return null;  
  14.    }  
  15. }//End of the BankFactory class.  
  1. class LoanFactory extends AbstractFactory{  
  2.    public Loan getLoan(String loan){  
  3.       if(loan == null){  
  4.          return null;  
  5.       }  
  6.       if(loan.equalsIgnoreCase("Home")){  
  7.          return new HomeLoan();  
  8.       } else if(loan.equalsIgnoreCase("Business")){  
  9.          return new BussinessLoan();  
  10.       } else if(loan.equalsIgnoreCase("Education")){  
  11.          return new EducationLoan();  
  12.       }  
  13.       return null;  
  14.    }  
  15. }  
Step 7: Create a FactoryCreator class to get the factories by passing an information such as Bank or Loan.
  1. class FactoryCreator {  
  2.      public static AbstractFactory getFactory(String choice){  
  3.       if(choice.equalsIgnoreCase("Bank")){  
  4.          return new BankFactory();  
  5.       } else if(choice.equalsIgnoreCase("Loan")){  
  6.          return new LoanFactory();  
  7.       }  
  8.       return null;  
  9.    }  
  10. }//End of the FactoryCreator.  
Step 8: Use the FactoryCreator to get AbstractFactory in order to get factories of concrete classes by passing an information such as type.
  1. import java.io.*;  
  2. class AbstractFactoryPatternExample {  
  3.       public static void main(String args[])throws IOException {
  4.       BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); 
  5.       System.out.print("Enter the name of Bank from where you want to take loan amount: ");  
  6.       String bankName=br.readLine();  
  7.       System.out.print("\n");  
  8.       System.out.print("Enter the type of loan e.g. home loan or business loan or education loan : ");  
  9.   
  10.      String loanName=br.readLine();  
  11.      AbstractFactory bankFactory = FactoryCreator.getFactory("Bank");  
  12.      Bank b=bankFactory.getBank(bankName);  
  13.   
  14.      System.out.print("\n");  
  15.      System.out.print("Enter the interest rate for "+b.getBankName()+ ": ");  
  16.   
  17. double rate=Double.parseDouble(br.readLine());  
  18. System.out.print("\n");  
  19. System.out.print("Enter the loan amount you want to take: ");  
  20.   
  21. double loanAmount=Double.parseDouble(br.readLine());  
  22. System.out.print("\n");  
  23. System.out.print("Enter the number of years to pay your entire loan amount: ");  
  24. int years=Integer.parseInt(br.readLine());  
  25.   
  26. System.out.print("\n");  
  27. System.out.println("you are taking the loan from "+ b.getBankName());  
  28.   
  29. AbstractFactory loanFactory = FactoryCreator.getFactory("Loan");  
  30.            Loan l=loanFactory.getLoan(loanName);  
  31.            l.getInterestRate(rate);  
  32.            l.calculateLoanPayment(loanAmount,years);  
  33.   }  
  34. }//End of the  AbstractFactoryPatternExample

Output

abstract factory pattern output

Comments

Popular posts from this blog

gsutil Vs Storage Transfer Service Vs Transfer Appliance

SQL basic interview question