许多东西如果概念化,时间久了容易遗忘,所以感觉最好举了例子来。举一反三,能够帮助更好地理解和记忆,甚至于回想。
----- 写在前面
代理模式:
网上教学,举的例子是坦克(implements Moveable),要记录它的move()时间,等等其他需求。
举一反三,租房子为例。
【 房东(Renter):被代理类; 中介(RenterProxy):代理类】
目的是将房子租出去(rent())(忽略细节部分,暂且假定houseProxy也有租房子的权利)
Interface: Renter
public interface Renter {
public void rent();
}
Class: HouseOwner
public class HouseOwner implements Renter{
@Override
public void rent() {
System.out.println("签订租房合同");
}
}
Class: AgentHandler
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class AgentHandler implements InvocationHandler {
private Object target;
public AgentHandler(Object target) {
super();
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
showHouse();
Object result = method.invoke(target, args);
afterServe();
return result;
}
public void showHouse(){
System.out.println("Show the house to a tenant.");
}
public void afterServe(){
System.out.println("If necessary, serve the tenant.");
}
}
Class: 测试类
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
public class AgentTest {
public static void main(String[] args) {
//房东
Renter renter = new HouseOwner();
InvocationHandler h = new AgentHandler(renter);
//中介
Renter renterProxy = (Renter)Proxy.newProxyInstance(renter.getClass().getClassLoader(),
renter.getClass().getInterfaces(), h);
//租房成功
renterProxy.rent();
}
}
例子到此告一段落。此为动态代理,即利用反射机制动态生成了代理类。后续:Spring的AOP。
本文通过实例详细介绍了代理模式的概念及应用,以租房场景为例,解释了如何使用代理模式简化对象交互过程,并演示了如何利用Java反射机制实现动态代理。
423

被折叠的 条评论
为什么被折叠?



