在看《Java编程思想》中复用类时,书中提到了代理模式。代理模式与继承,组合同为复用类的方式。
- 组合:在新的类中使用现有类的对象(使用现有类功能而非其接口)。
- 继承:按照现有类的类型来创建新类(使用现有类的一个特殊版本,如轿车是汽车的一个特殊版本)。
- 代理:将现有类置于对象中,同时在新类中暴露该对象的方法。
其实代理分为静态代理与动态代理,这里所说的是静态代理。动态代理的知识推荐这篇文章:java的动态代理机制详解
用途
代理用途很多,比如它有保护对象的功能。假如我创建了一个只想让特定用户访问的类的对象,就可以通过代理进行权限控制。
下面就以一个例子说明代理模式。
class Person {
//简洁考虑不写get函数了
String identity;
Person(String str) {
identity = str;
}
}
class MyHouse {
void openDoor() {};
void sleep() {};
}
//任何想要进房子的人都必须经过guard
class MyHouseGuard {
MyHouse house = new MyHouse();
void openDoor(Person person) {
//只为owner开门
if(person.identity.equals("owner")) {
house.openDoor();
}
}
}
public class Test {
public static void main(String[] args) {
Person thief = new Person("thief");
Person owner = new Person("owner");
MyHouseGuard guard = new MyHouseGuard();
guard.openDoor(thief); //fail
guard.openDoor(owner); //success
}
}
代码中MyHouseGuard即为MyHouse提供代理的类,其中既组合了MyHouse,又暴露了MyHouse的openDoor方法。