Factory Design Pattern

Factory Design Pattern:

This is most used design pattern in Java. Factory pattern also called as Factory method design pattern.

Factory design pattern comes under creational pattern. This pattern provides one of the best ways to create an object.

By this pattern we create object without exposing creation logic of these objects to the users.

This pattern not only used in JDK but also in various Open Source frameworks such as Struts, Wicket, spring and Apache along with decorator design pattern in Java. Factory Design pattern is based on Encapsulation object oriented concept.

Example Code:

package Factory;

public interface Loan {

public int getInterestRate();

}

 

package Factory;

public class CarLoan implements Loan{

@Override

public int getInterestRate() {

return 12;

}

}

 

package Factory;

public class HomeLoan implements Loan{

@Override

public int getInterestRate() {

return 10;

}

}

 

package Factory;

public class PersonalLoan implements Loan{

@Override

public int getInterestRate() {

return 14;

}

}

package Factory;

public class LoanFactory {

public Loan getFactory(String loanType) {

if ( loanType.equals(“car”) )

return new CarLoan();

else if ( loanType.equals(“home”) )

return new HomeLoan();

else if ( loanType.equals(“personal”) )

return new PersonalLoan();

return null;

}

}

 

package Factory;

public class FactoryPatternDemo {

/**

* @param args

*/

public static void main(String[] args) {

LoanFactory loanFactory = new LoanFactory();

Loan lncar = loanFactory.getFactory(“car”);

System.out.println(“Car Loan Interset rate->”+lncar.getInterestRate());

Loan lnper = loanFactory.getFactory(“personal”);

System.out.println(“Personal Loan Interset rate->”+lnper.getInterestRate());

Loan lnhome = loanFactory.getFactory(“home”);

System.out.println(“Home Loan Interset rate->”+lnhome.getInterestRate());

}

}

java

Leave a Reply

Your email address will not be published. Required fields are marked *