代理模式(Proxy Pattern)

2014-11-24 11:10:37 · 作者: · 浏览: 1

使用简单的对象来代替一个复杂的对象或者为另一个对象提供一个占位符来控制对它的访问。经典UML类如下:


使用场合和优势:


实时或是在内存中创建一个对象代价太高的情况下。
延迟创建直到你需要实际的对象。
加载大的图像。
在网络的高峰时间段加载远程对象。
对于一个复杂的系统,必须使用访问权限时,需要使用代理模式。
从JDK 1.3 开始,java 就对实现代理设计模式有直接的支持。我们没有必要在引用和对象创建对象上担心,因为Java提供给我们所需要的实用类。下面这个例子阐明了如何使用Java API 的代理设计模式。
定义一个动物接口。
[java]
public interface Animal {

public void getSound();

}

public interface Animal {

public void getSound();

}


Animal的子类Lion。
[java]
public class Lion implements Animal {

public void getSound() {
System.out.println("lion roars");
}
}

public class Lion implements Animal {

public void getSound() {
System.out.println("lion roars");
}
}
调用类AnimalInvocationHandler。
[java]
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**
* @author JohnLiu
*/
public class AnimalInvocationHandler implements InvocationHandler {
public AnimalInvocationHandler(Object realSubject) {
this.realSubject = realSubject;
}

public Object invoke(Object proxy, Method m, Object[] args) {
Object result = null;
try {
result = m.invoke(realSubject, args);
} catch (Exception ex) {
ex.printStackTrace();
}
return result;
}

private Object realSubject = null;
}

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**
* @author JohnLiu
*/
public class AnimalInvocationHandler implements InvocationHandler {
public AnimalInvocationHandler(Object realSubject) {
this.realSubject = realSubject;
}

public Object invoke(Object proxy, Method m, Object[] args) {
Object result = null;
try {
result = m.invoke(realSubject, args);
} catch (Exception ex) {
ex.printStackTrace();
}
return result;
}

private Object realSubject = null;
}
测试调用proxy模式的具体形式。
[java]
public class ProxyDemo {
public static void main(String[] args) {
Animal realSubject = new Lion();
Animal proxy = (Animal) Proxy.newProxyInstance(realSubject.getClass()
.getClassLoader(), realSubject.getClass().getInterfaces(),
new AnimalInvocationHandler(realSubject));
proxy.getSound();
}
}

public class ProxyDemo {
public static void main(String[] args) {
Animal realSubject = new Lion();
Animal proxy = (Animal) Proxy.newProxyInstance(realSubject.getClass()
.getClassLoader(), realSubject.getClass().getInterfaces(),
new AnimalInvocationHandler(realSubject));
proxy.getSound();
}
}
运行结果:
[sql]
lion roars

lion roars
Java API中有具体proxy模式的实现,如果感兴趣,请查阅有关的源文件。
Java RMI , Java 远程方法调用,这个包中运用了远程代理模式。
Security Proxy , Java的安全控制机制中叶采用了代理模式。