-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathCalculateElectricityBill.java
76 lines (60 loc) · 1.79 KB
/
CalculateElectricityBill.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package Solutions;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
//Calculate Electricity Bill : A Real World Example of Factory Method
abstract class Plan {
protected double rate;
abstract void getRate();
public void calculateBill(int units) {
System.out.println(units * rate);
}
}
class DomesticPlan extends Plan {
// @override
public void getRate() {
rate = 3.50;
}
}
class CommercialPlan extends Plan {
// @override
public void getRate() {
rate = 7.50;
}
}
class InstitutionalPlan extends Plan {
// @override
public void getRate() {
rate = 5.50;
}
}
class GetPlanFactory {
public Plan getPlan(String planType) {
if (planType == null) {
return null;
}
if (planType.equalsIgnoreCase("DOMESTICPLAN")) {
return new DomesticPlan();
} else if (planType.equalsIgnoreCase("COMMERCIALPLAN")) {
return new CommercialPlan();
} else if (planType.equalsIgnoreCase("INSTITUTIONALPLAN")) {
return new InstitutionalPlan();
}
return null;
}
}
public class CalculateElectricityBill {
public static void main(String args[]) throws IOException {
GetPlanFactory planFactory = new GetPlanFactory();
System.out.print("Enter the name of plan 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());
Plan 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);
}
}