Skip to content

Commit 44cc4f4

Browse files
authored
Merge pull request lingcoder#30 from qq379797807/master
8章写了一点点
2 parents 456e3e6 + 145fbcc commit 44cc4f4

File tree

1 file changed

+37
-1
lines changed

1 file changed

+37
-1
lines changed

docs/book/08-Reuse.md

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,43 @@
1818

1919
<!-- Composition Syntax -->
2020
## 组合语法
21-
21+
在前面的学习中,“组合”(**Composition**)已经被多次使用。你仅需要把对象的引用(**object references**)放置在一个新的类里,这就使用了组合。例如,假设你需要一个对象,其中内置了几个String对象,两个基本类型(**primitives**)的属性字段,一个自定义Class的对象。对于非基本类型对象,将引用直接放置在Class中,对于基本类型属性字段则仅进行声明(**define**)。
22+
// reuse/SprinklerSystem.java
23+
// Composition for code reuse
24+
class WaterSource {
25+
private String s;
26+
WaterSource() {
27+
System.out.println("WaterSource()");
28+
s = "Constructed";
29+
}
30+
@Override
31+
public String toString() { return s; }
32+
}
33+
public class SprinklerSystem {
34+
private String valve1, valve2, valve3, valve4;
35+
private WaterSource source = new WaterSource();
36+
private int i;
37+
private float f;
38+
@Override
39+
public String toString() {
40+
return
41+
"valve1 = " + valve1 + " " +
42+
"valve2 = " + valve2 + " " +
43+
"valve3 = " + valve3 + " " +
44+
"valve4 = " + valve4 + "\n" +
45+
"i = " + i + " " + "f = " + f + " " +
46+
"source = " + source; // [1]
47+
}
48+
public static void main(String[] args) {
49+
SprinklerSystem sprinklers = new SprinklerSystem();
50+
System.out.println(sprinklers);
51+
}
52+
}
53+
/* Output:
54+
WaterSource()
55+
valve1 = null valve2 = null valve3 = null valve4 = null
56+
i = 0 f = 0.0 source = Constructed
57+
*/
2258

2359
<!-- Inheritance Syntax -->
2460
## 继承语法

0 commit comments

Comments
 (0)