Wednesday, June 21, 2017

FactoryDemo Using Interface

Tags

Following code will help in selecting plan using Run Time Polymorphism:

Code:
interface Plan{
void setDataAndPrice();
void showPlan();
}

class Plan2G implements Plan{
int data,price;
Plan2G(){
setDataAndPrice();
}
public void setDataAndPrice() {
data=1024;
price=70;
}
public void showPlan(){
System.out.println("----Plan Details---");
System.out.println("Data: "+data+"Gb---"+"Price: \u20b9"+price);
}
}
class Plan3G implements Plan{
int data,price;
Plan3G(){
setDataAndPrice();
}
public void setDataAndPrice() {
data=1024;
price=150;
}
public void showPlan(){
System.out.println("----Plan Details---");
System.out.println("Data: "+data+"Gb---"+"Price: \u20b9"+price);
}
}

class Plan4G implements Plan{
int data,price;
Plan4G(){
setDataAndPrice();
}
public void setDataAndPrice() {
data=1024;
price=250;
}
public void showPlan(){
System.out.println("----Plan Details---");
System.out.println("Data: "+data+"Gb---"+"Price: \u20b9"+price);

}
}

class PlanFactory{
static Plan p;
static Plan getPlan(int a) {
switch(a){
case 2: 
p=new Plan2G();
break;
case 3:
p=new Plan3G();
break;
case 4:
p=new Plan4G();
break;
}
return p;
}

}

public class FactoryDemo {

public static void main(String[] args) {

Plan plan = PlanFactory.getPlan(2);
plan.showPlan();
plan = PlanFactory.getPlan(3);
plan.showPlan();
plan = PlanFactory.getPlan(4);
plan.showPlan();
        
}
}
Output: