类与类之间的关系除了有组合和继承外还有代理。Java并没有对代理具有直接显式的支持。代理使得一个成员对象就像组合那样放置于类中作为类的一个子成员,同时在新类中定义函数以暴露原类的所有方法,就像继承一样。Thinking in Java 中给出的例子如下:
import static net.mindview.util.Print.*;
public class SpaceShipControls {
/**
*
* @param velocity
*/
public void up(int velocity) {
print("Space ship up with velocity!");
}
/**
*
* @param velocity
*/
public void down(int velocity) {
print("Space ship go down with velocity: " + velocity);
}
/**
*
* @param velocity
*/
public void left(int velocity) {
print("Space ship go left with velocity: " + velocity);
}
/**
*
* @param velocity
*/
public void right(int velocity) {
print("Space ship go right with velocity: " + velocity);
}
/**
*
* @param velocity
*/
public void forward(int velocity) {
print("Space ship forward with velocity: " + velocity);
}
/**
*
* @param velocity
*/
public void back(int velocity) {
print("Space ship go back with velocity: " + velocity);
}
/**
*
*/
public void turboBoost() {
print("Space ship speed up!");
}
}
SpaceShip.java
import static net.mindview.util.Print.print;
/**
* @author MTT
*
*/
public class SpaceShip {
private String name;
private SpaceShipControls controls = new SpaceShipControls();
public SpaceShip(String name) {
this.name = name;
}
/**
* Delegated method
* @param velocity
*/
public void up(int velocity) {
controls.up(velocity);
}
/**
* Delegated method
* @param velocity
*/
public void down(int velocity) {
controls.down(velocity);
}
/**
* Delegated method
* @param velocity
*/
public void left(int velocity) {
controls.left(velocity);
}
/**
* Delegated method
* @param velocity
*/
public void right(int velocity) {
controls.right(velocity);
}
/**
* Delegated method
* @param velocity
*/
public void forward(int velocity) {
controls.forward(velocity);
}
/**
* Delegated method
* @param velocity
*/
public void back(int velocity) {
controls.back(velocity);
}
/**
* Delegated method
*/
public void turboBoost() {
controls.turboBoost();
}
}
代理使得control类的具体实现与spaceship类完全隔离,演进一步就会类似于spring的依赖注入。如果使用spring的依赖注入,控制反转,可以使得上程序中
private SpaceShipControls controls = new SpaceShipControls();
SpaceShipControls()可以在config中配置,交由spring来创建。保证spaceship模块与control模块的松耦合。
接口
实现接口同样能够实现所希望的控制功能,但是如果使用spaceship直接implement 类spaceShipControls,就会造成spaceShip类与SpaceShipControls模块耦合度太高,很难进行后期的维护与扩展。
代理与接口的结合才能更好的发挥面向对象的优势。