-
Notifications
You must be signed in to change notification settings - Fork 7
/
OpenClosed_counter.java
97 lines (83 loc) · 2.81 KB
/
OpenClosed_counter.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package src;
/**
* 这个例子违反了开闭原则,为了演示方便把其他类作为子类放在一起。
* 1. 车辆制造类将具体创建方法放在了一起,不利于扩展。
* 2. 一旦有新的车辆类型加入就需要不断修改车辆建造类。
*/
public class OpenClosed_counter {
public OpenClosed_counter() {
return;
}
public class Vehicle {
public String name;
public int type;
public int weight;
public String getName() {
return this.name;
}
}
public class Car extends Vehicle {
public String name = "car";
public int type = 1;
public int weight = 2500;
public Car(String name) {
this.name = name;
super.type = this.type;
}
@Override
public String getName() {
return this.name;
}
}
public class Bus extends Vehicle {
public String name = "bus";
public int type = 2;
public int weight = 15000;
public Bus(String name) {
this.name = name;
super.type = this.type;
}
@Override
public String getName() {
return this.name;
}
}
public class VehicleFactory {
public VehicleFactory() {
return;
}
public Vehicle createVehicle(Vehicle vehicle) {
// 从工厂里调用具体对象的方法,避免通过if else/switch 判断来区分对象。
// 当增加其他具体对象时就会需要修改这里的方法,这样就就违背了对修改关闭,对扩展开放原则。
// 好的做法是这个方法里具体对象直接往下传递,不做逻辑处理,从而方便扩展。
switch (vehicle.type) {
case 1:
createCar(vehicle);
break;
case 2:
createBus(vehicle);
break;
// 如果新增其他对象则需要不断修改
// case 3:
// createVan(vehicle);
// break;
default:
break;
}
// 可以返回具体对象或者调用基础方法
return vehicle;
}
public Vehicle createCar(Vehicle vehicle) {
// doSomething
Car car = (Car) vehicle;
System.out.println("car has been produced: " + " " + car.type + " " + car.name + " " + car.weight);
return vehicle;
}
public Vehicle createBus(Vehicle vehicle) {
// doSomething
Bus bus = (Bus) vehicle;
System.out.println("bus has been produced: " + " " + bus.type + " " + bus.name + " " + bus.weight);
return vehicle;
}
}
}