Factory Pattern
Factory Pattern is way to create object in such Way using Common Interface without exposing the creation logic
Simple Example
Example:
step 1. creation of interface.
public interface BANK {
double getIntrest();
}
step 2.
implementation of interface for BOB.
public class BOB implements BANK {
@Override
public double getIntrest() {
return 8.7;
}
}
step 3.
implementation of interface for SBI
.
public class SBI implements BANK{
@Override
public double getIntrest() {
return 5.7;
}
}
step 4.
implementation of interface for UNION .
public class UNION implements BANK{
@Override
public double getIntrest() {
return 10.2;
}
}
step 5.
class Imp to get Factory Based on input from user.
public class Factory {
public BANK getBank(String bankName) {
switch (bankName) {
case "SBI":
return new SBI();
case "BOB":
return new BOB();
case "UNION":
return new UNION();
}
return null;
}
}
step 6.
public class BankTest {
public static void main(String[] args) {
Factory ff=new Factory();
BANK bank = ff.getBank("SBI");
double intrest = bank.getIntrest();
System.out.println("Interest is:"+intrest);
}
}
Result:
Interest is:5.7
Comments
Post a Comment