代理模式
定义: 代理模式给某一个对象提供一个代理对象,并由代理对象控制原对象的引用。用贴近生活的例子来说,代理模式就好比我们常见的中介。
下面用一个简单的例子简单演示一下代理模式,
场景;房屋出租,房东,中介,客户三者是怎样一个关系。
代理模式分静态代理和动态代理两种模式
公共接口
Rent.java
package com.ys.Dao;
public interface Rent {
void rent();
}
静态代理
房东
Host.java
package com.ys.pojo.static_proxy;
import com.ys.Dao.Rent;
public class Host implements Rent {
@Override
public void rent() {
System.out.println("房东出租房子");
}
}
中介
Proxy.java
package com.ys.pojo.static_proxy;
import com.ys.Dao.Rent;
public class Proxy implements Rent {
private Host host;
public Host getHost() {
return host;
}
public void setHost(Host host) {
this.host = host;
}
public Proxy(Host host) {
this.host = host;
}
@Override
public void rent() {
seehouse();
host.rent();
hetong();
}
public void hetong() {
System.out.println("签合同");
}
public void seehouse() {
System.out.println("带客户去看房");
}
}
客户
package com.ys.pojo.static_proxy;
public class Client {
public static void main(String[] args) {
Host host = new Host();
Proxy proxy = new Proxy(host);
proxy.rent();
}
}
测试:
动态代理
代理调用处理程序 ProxyInvocationHandler.java
package com.ys.pojo.dynamic_proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class ProxyInvocationHandler implements InvocationHandler {
private Object target;
public void setRent(Object target) {
this.target = target;
}
public Object getProxy(){
return Proxy.newProxyInstance(this.getClass().getClassLoader(),target.getClass().getInterfaces(), this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result = method.invoke(target, args);
return result;
}
}
房东
Host.java
package com.ys.pojo.dynamic_proxy;
public class Host implements Rent{
@Override
public void rent() {
System.out.println("出租房子");
}
}
测试
package com.ys.pojo.dynamic_proxy;
public class Client {
public static void main(String[] args) {
Host host = new Host();
ProxyInvocationHandler pih = new ProxyInvocationHandler();
pih.setRent(host);
Rent proxy = (Rent) pih.getProxy();
proxy.rent();
}}
|