Factory Design Pattern Electricity Bill
Step 1
import java.io.*;
abstract class ELectricityBill
{ protected double rate;
abstract void getRate();
public void calculateBill(int units)
{
System.out.println(units * rate);
}
}
Step 2
public class ResidentialBill extends ELectricityBill {
@Override
public void getRate() {
rate = 2.2; }
}
Step 3
public class commercialBill extends ELectricityBill {
@Override
public void getRate() {
rate = 9.87;
}
}
Step 4
public class GetPlanFactory {
// use getPlan method to get object of type ELectricityBill
public ELectricityBill getPlan(String planType) {
if (planType == null) {
return null;
}
if (planType.equalsIgnoreCase("ResidentialBill")) {
return new ResidentialBill();
}
else if (planType.equalsIgnoreCase("commercialBill")) {
return new commercialBill();
}
return null;
}
}
Step 5
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class GenerateBill {
public static void main(String args[]) throws IOException {
GetPlanFactory planFactory = new GetPlanFactory();
// get an object of DomesticPaln and call its getPlan()method.But we want to
// calculate the bill for one plan at time not all.for this we IO concept.
System.out.print("Enter the name of ElectricityBill for which the bill will be
generated: ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String planName = br.readLine();
System.out.print("Enter the number of units for bill will be calculated: ");
int units = Integer.parseInt(br.readLine());
ELectricityBill p = planFactory.getPlan(planName);
// call getRate() method and calculateBill()method of DomesticPaln.
System.out.print("Bill amount for " + planName + " of " + units + " units is: ");
p.getRate();
p.calculateBill(units);
}
}
Output
Enter the name of ElectricityBill for which the bill will be generated: residentialBill
Enter the number of units for bill will be calculated: 89
Bill amount for residentialBill of 89 units is: 195.8
BUILD SUCCESSFUL (total time: 31 seconds)