要想完成這個案例,首先了解,什么是AOP


如上圖,有兩個類,A類和B類,
我們可以通過AOP,實作在使用A類的methodA方法之前,先呼叫B類的methodb1()方法,然后再執行自己的mehodA()方法,再呼叫B類的methodb2()方法,
在了解了AOP的概念知道呢,我們就可以來對該案例進行分析了

如上圖,我們想要在老總類呼叫eat()吃的方法時,秘書類先呼叫自己的daojiu()倒酒方法,然后老總類再呼叫自己的eat()方法,最后秘書類再呼叫自己的huazi()方法.
思維導圖:

代碼如下:
ILaoZong
package com.lbl.proxy;
public interface ILaoZong {
void eat();
}
LaoZongImpl
package com.lbl.proxy;
public class LaoZongImpl implements ILaoZong {
@Override
public void eat() {
System.out.println("吃三下鍋");
}
}
MiShu
package com.lbl.proxy;
public class MiShu {
public void dianyan(){
System.out.println("點煙");
}
public void daojiu(){
System.out.println("倒酒");
}
}
proxyTest
@Test
public void test01(){
LaoZongImpl laoZong = new LaoZongImpl();
MiShu miShu = new MiShu();
ClassLoader classLoader=LaoZongImpl.class.getClassLoader();
Class[] interfaces = {ILaoZong.class};
InvocationHandler handler=new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
miShu.daojiu();
Object returnVal = method.invoke(laoZong, args);
miShu.dianyan();
return returnVal;
}
};
ILaoZong iLaoZong = (ILaoZong) Proxy.newProxyInstance(classLoader,interfaces , handler);
iLaoZong.eat();
}
運行結果:

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/168178.html
標籤:其他
