代理模式定义
代理模式 是指为其余对象提供一种代理,以管制对这个对象的拜访
动态代理模式
demo:大部分的房主会把房子交给中介去出租,那么这个场景就是房主是实在类,中介是代理类(帮忙房主出租房子),间接上代码
顶层接口
public interface IBuyHouse {
void renting();
}
房主
public class Homeowner implements IBuyHouse {
@Override
public void renting() {
System.out.println("customer: i want to buy house");
}
}
中介
public class IntermediaryProxy implements IBuyHouse {
private IBuyHouse iBuyHouse;
public IntermediaryProxy(IBuyHouse iBuyHouse) {
this.iBuyHouse = iBuyHouse;
}
@Override
public void renting() {
before();
iBuyHouse.renting();
after();
}
private void before() {
System.out.println("中介和客户沟通 ,要找一个什么样的房子");
}
private void after() {
System.out.println("达成协议,交定金");
}
}
测试
public static void main(String[] args) {
IBuyHouse iBuyHouse = new IntermediaryProxy(new Homeowner());
iBuyHouse.renting();
}
这样就实现了一个代理类的调用
接下来咱们,咱们看看如何实现动静代理
动静代理(java)
中介(代理类)
public class IntermediaryProxy implements InvocationHandler {
private IBuyHouse target;
public IBuyHouse instance(IBuyHouse target){
this.target = target;
Class<? extends IBuyHouse> aClass = target.getClass();
return (IBuyHouse) Proxy.newProxyInstance(aClass.getClassLoader(), aClass.getInterfaces(), this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
before();
Object invoke = method.invoke(this.target, args);
after();
return invoke;
}
private void before() {
System.out.println("中介和客户沟通 ,要找一个什么样的房子");
}
private void after() {
System.out.println("达成协议,交定金");
}
}
// 调用
public static void main(String[] args) {
IBuyHouse instance = new IntermediaryProxy().instance(new Homeowner());
instance.renting();
}
通过Proxy.newProxyInstance(…)创立一个代理类,而后调用重写的invoke办法去实现逻辑。
以上是jdk提供的一种办法,接下来咱们用Cglib实现一下
cglib实现动静代理
public class IntermediaryProxy implements MethodInterceptor {
public Object instance(Class<?> clazz){
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(clazz);
enhancer.setCallback(this);
return enhancer.create();
}
@Override
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
before();
methodProxy.invokeSuper(o, objects);
after();
return null; }
private void before() {
System.out.println("中介和客户沟通 ,要找一个什么样的房子");
}
private void after() {
System.out.println("达成协议,交定金");
}
}
// 调用
public static void main(String[] args) {
Homeowner homeowner = (Homeowner) new IntermediaryProxy().instance(Homeowner.class);
homeowner.renting();
homeowner.getMoney();
}
用cglib实现动静代理是不须要通过接口的 也就是之前的IBuyHouse 是不须要创立的,cglib代理类是间接继承实在类去实现代理的。
发表回复