场景描述:
需要实现某个行为时为了解耦而使用,举例:需求(A需要租房,房东需要出租)使用代理模式就是:A进入一家中介所(代理类),A就完成了租房行为。 后续就是代理对象的一系列操作。中介找房东出租(真实对象)。而中介所不仅包含出租签合同一件事,还可植入一系列操作。比如让A关注他家公众号~
代码实现:
//###########静态代理
// 出租房接口
interface MyInterface {
void doSomething();
}
// 真实对象 房东
class RealObject implements MyInterface {
public void doSomething() {
// 实际操作
System.out.println("单间要出租!2000/月");
}
}
// 代理对象 中介所
class ProxyObject implements MyInterface {
private RealObject realObject;
public ProxyObject(RealObject realObject) {
this.realObject = realObject;
}
public void doSomething() {
// 可以在这里添加额外的逻辑
System.out.println("关注公众号");
realObject.doSomething();
// 可以在这里添加额外的逻辑
System.out.println("中介加收中介费1000元,请A提供材料准备签合同");
}
}
// A
public void A() {
ProxyObject proxyObject = new ProxyObject(new RealObject());
proxyObject.doSomething();
}
//###########动态代理
// 租房接口
interface MyInterface {
void doSomething();
}
// 跑腿接口
interface MyInterface2 {
void doProxyRun();
}
// 真实对象 A
class RealObject2 implements MyInterface2 {
@Override
public void doProxyRun() {
System.out.println("送材料");
}
}
// 真实对象 房东
class RealObject implements MyInterface {
public void doSomething() {
// 实际操作
System.out.println("单间要出租!2000/月");
}
}
// 自定义InvocationHandler(动态代理核心) - 好比大型代理管理平台
class MyInvocationHandler implements InvocationHandler {
private Object realObject;
public MyInvocationHandler(Object realObject) {
this.realObject = realObject;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result;
if (proxy instanceof MyInterface) {
// 可以在这里添加额外的逻辑
System.out.println("关注公众号");
result = method.invoke(realObject, args);
// 可以在这里添加额外的逻辑
System.out.println("中介加收中介费1000元,请A提供材料准备签合同");
return result;
}else if (proxy instanceof MyInterface2) {
System.out.println("前往取材料");
result = method.invoke(realObject, args);
// 可以在这里添加额外的逻辑
System.out.println("送材料到指定处");
System.out.println("确认完成订单,收取费用100元");;
return result;
}
return method.invoke(realObject, args);
}
}
public void A() {
// 租房代理
MyInvocationHandler handler = new MyInvocationHandler(new RealObject());
// 租房代理
MyInterface proxy = (MyInterface) Proxy.newProxyInstance(
MyInterface.class.getClassLoader(),
new Class[]{MyInterface.class},
handler
);
// 跑腿
MyInterface2 proxy2 = (MyInterface2)Proxy.newProxyInstance(MyInterface2.class.getClassLoader(), new Class[]{MyInterface2.class}, new MyInvocationHandler(new RealObject2()));
proxy.doSomething();
System.out.println("A没时间,再小程序上下单了跑腿代理");
proxy2.doProxyRun();
}