-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathCompositeReuse_counter.java
73 lines (61 loc) · 2.02 KB
/
CompositeReuse_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
package src;
/**
* 这个例子违反了组合复用原则,因为采用了继承而不是组合。
* 1. 人的身份会有多重角色,不是适合继承人,如果是物种角度可以是继承,比如男、女继承人。
* 2. 采用继承会使得不够灵活,修改起来很麻烦,例如一个人既是经理也是雇员。
*/
public class CompositeReuse_counter {
public CompositeReuse_counter() {
return;
}
// 顶级抽象父类
public abstract class Person {
public String name;
public int age;
public int gender;
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
// 雇员父类继承了Person类,这里违反了组合复用原则,不利于扩展
public class Employee extends Person {
public int id;
public String title;
public boolean work() {
return true;
}
}
// 具体职位类
public class Engineer extends Employee {
public Engineer(String name, int age, int id, String title) {
this.name = name;
this.age = age;
this.id = id;
this.title = title;
}
@Override
public boolean work() {
System.out.println("Engineer is working." + " id = " + this.id
+ ", title = " + this.title + " name = " + this.getName() + ", age = " + this.getAge());
return true;
}
}
// 具体职位类
public class Manager extends Employee {
public Manager(String name, int age, int id, String title) {
this.name = name;
this.age = age;
this.id = id;
this.title = title;
}
@Override
public boolean work() {
System.out.println("Manager is working." + " id = " + this.id
+ ", title = " + this.title + " name = " + this.getName() + ", age = " + this.getAge());
return true;
}
}
}