Calculate Electricity Bill : A Real World Example of Factory Method
Step 1: Create a Plan abstract class.
import [Link].*;
abstract class Plan{
protected double rate;
abstract void getRate();
public void calculateBill(int units){
[Link](units*rate);
}
}//end of Plan class.
Step 2: Create the concrete classes that extends Plan abstract class.
class DomesticPlan extends Plan{
//@override
public void getRate(){
rate=3.50;
}
}//end of DomesticPlan class.
class CommercialPlan extends Plan{
//@override
public void getRate(){
rate=7.50;
}
/end of CommercialPlan class.
class InstitutionalPlan extends Plan{
//@override
public void getRate(){
rate=5.50;
}
/end of InstitutionalPlan class.
Step 3: Create a GetPlanFactory to generate object of concrete classes based on
given information..
class GetPlanFactory{
//use getPlan method to get object of type Plan
public Plan getPlan(String planType){
if(planType == null){
return null;
}
if([Link]("DOMESTICPLAN")) {
return new DomesticPlan();
}
else if([Link]("COMMERCIALPLAN")){
return new CommercialPlan();
}
else if([Link]("INSTITUTIONALPLAN")) {
return new InstitutionalPlan();
}
return null;
}
}//end of GetPlanFactory class.
Step 4: Generate Bill by using the GetPlanFactory to get the object of concrete
classes by passing an information such as type of plan DOMESTICPLAN or
COMMERCIALPLAN or INSTITUTIONALPLAN.
import [Link].*;
class GenerateBill{
public static void main(String args[])throws IOException{
GetPlanFactory planFactory = new GetPlanFactory();
[Link]("Enter the name of plan for which the bill will be
generated: ");
BufferedReader br=new BufferedReader(new InputStreamReader([Link]));
String planName=[Link]();
[Link]("Enter the number of units for bill will be calculated: ");
int units=[Link]([Link]());
Plan p = [Link](planName);
//call getRate() method and calculateBill()method of DomesticPaln.
[Link]("Bill amount for "+planName+" of "+units+" units is: ");
[Link]();
[Link](units);
}
}//end of GenerateBill class.