类的复用 ,主要有 组合、继承、代理 三种方式。
7.1组合,就是 has-a的关系,而非 is-a.
package com.caolh._7ReusingClass;//: reusing/_7_1SprinklerSystem.java
// Composition for code reuse.
class WaterSource {
private String s;
WaterSource() {
System.out.println("WaterSource()");
s = "Constructed";
}
public String toString() { return s; }
}
//喷水灭火系统
public class _7_1SprinklerSystem {
private String valve1, valve2, valve3, valve4;
private WaterSource source = new WaterSource(); // 我有一个水源 has -a
private int i;
private float f;
public String toString() {
return
"valve1 = " + valve1 + " " +
"valve2 = " + valve2 + " " +
"valve3 = " + valve3 + " " +
"valve4 = " + valve4 + "\n" +
"i = " + i + " " + "f = " + f + " " +
"source = " + source;
}
public static void main(String[] args) {
_7_1SprinklerSystem sprinklers = new _7_1SprinklerSystem();
System.out.println(sprinklers);
}
} /* Output:
WaterSource()
valve1 = null valve2 = null valve3 = null valve4 = null
i = 0 f = 0.0 source = Constructed
*///:~
7.2继承
package com.caolh._7ReusingClass;//: reusing/_7_2Chess.java
// Inheritance, constructors and arguments.
class Game {
Game(int i) {
System.out.println("Game constructor");
}
}
class BoardGame extends Game {
BoardGame(int i) {
super(i);
System.out.println("BoardGame constructor");
}
}
public class _7_2Chess extends BoardGame {
_7_2Chess() {
super(11); //父亲的构造器没有super()无参构造器,所以要自己指定
System.out.println("Chess constructor");
}
public static void main(String[] args) {
_7_2Chess x = new _7_2Chess();
}
} /* Output:
Game constructor
BoardGame constructor
Chess constructor
*///:~
7.3代理的方式
package com.caolh._7ReusingClass;//: reusing/_7_3SpaceShipDelegation.java
class SpaceShipControls {
void up(int velocity) {}
void down(int velocity) {}
void left(int velocity) {}
void right(int velocity) {}
void forward(int velocity) {}
void back(int velocity) {}
void turboBoost() {}
} ///:~
public class _7_3SpaceShipDelegation {
private String name;
private SpaceShipControls controls =
new SpaceShipControls();
public _7_3SpaceShipDelegation(String name) {
this.name = name;
}
// Delegated methods:
//太空飞船代理了 飞船控制器
public void back(int velocity) {
controls.back(velocity);
}
public void down(int velocity) {
controls.down(velocity);
}
public void forward(int velocity) {
controls.forward(velocity);
}
public void left(int velocity) {
controls.left(velocity);
}
public void right(int velocity) {
controls.right(velocity);
}
public void turboBoost() {
controls.turboBoost();
}
public void up(int velocity) {
controls.up(velocity);
}
public static void main(String[] args) {
_7_3SpaceShipDelegation protector =
new _7_3SpaceShipDelegation("NSEA Protector");
protector.forward(100);
}
} ///:~