AOP,《thinking in java 4th》中没有过多阐述,只能结合视频和查找其他资料了。
AOP的大概原理是这样的:
设计模式高深了,咱连皮毛都触不到,目前知道这个就行了。
下面是谈不上设计模式的建议代码实践:
1 import java.lang.reflect.InvocationHandler;
2 import java.lang.reflect.Method;
3 import java.lang.reflect.Proxy;
4
5 public class Test {
6
7 //接口,攒电脑
8 public interface DIY{
9 //去中关村买配件
10 public void buySomthin();
11
12 }
13
14 //我要去中关村攒电脑
15 public class DIYPC implements DIY{
16 public DIYPC(){
17 System.out.println("天气不错,攒电脑去");
18 }
19
20 @Override
21 public void buySomthin() {
22 // TODO Auto-generated method stub
23 System.out.println("买配件");
24
25 }
26
27 }
28
29 //实现攒电脑的奸商代理
30 public class DIYHandler implements InvocationHandler{
31
32 private Object objProxy;
33
34 public DIYHandler(Object obj){
35 this.objProxy=obj;
36 }
37
38 @Override
39 public Object invoke(Object proxy, Method method, Object[] args)
40 throws Throwable {
41 // TODO Auto-generated method stub
42 System.out.println(" "+objProxy.getClass().getSimpleName()+"-"+method.getName());
43
44
45 return method.invoke(objProxy, args);
46 }
47
48 }
49
50 public static void JianShang(DIY diyProxy){
51 System.out.println("尼玛奸商的都是返修货");
52
53 //Proxy.newProxyInstance会动态实现目标的接口,并调用代理的invoke方法,
54 //然后通过类加载器,动态的调用这个新生成的class并返回
55 diyProxy.buySomthin();
56 System.out.println("js笑了,我内牛满面了");
57 }
58
59 public static void main(String[] args){
60 Test t=new Test();
61 DIY diy=t.new DIYPC();
62 DIY diyProxy=(DIY)Proxy.newProxyInstance(diy.getClass().getClassLoader(), diy.getClass().getInterfaces(), t.new DIYHandler(diy));
63 JianShang(diyProxy);
64
65 }
66
67
68 }
2 import java.lang.reflect.Method;
3 import java.lang.reflect.Proxy;
4
5 public class Test {
6
7 //接口,攒电脑
8 public interface DIY{
9 //去中关村买配件
10 public void buySomthin();
11
12 }
13
14 //我要去中关村攒电脑
15 public class DIYPC implements DIY{
16 public DIYPC(){
17 System.out.println("天气不错,攒电脑去");
18 }
19
20 @Override
21 public void buySomthin() {
22 // TODO Auto-generated method stub
23 System.out.println("买配件");
24
25 }
26
27 }
28
29 //实现攒电脑的奸商代理
30 public class DIYHandler implements InvocationHandler{
31
32 private Object objProxy;
33
34 public DIYHandler(Object obj){
35 this.objProxy=obj;
36 }
37
38 @Override
39 public Object invoke(Object proxy, Method method, Object[] args)
40 throws Throwable {
41 // TODO Auto-generated method stub
42 System.out.println(" "+objProxy.getClass().getSimpleName()+"-"+method.getName());
43
44
45 return method.invoke(objProxy, args);
46 }
47
48 }
49
50 public static void JianShang(DIY diyProxy){
51 System.out.println("尼玛奸商的都是返修货");
52
53 //Proxy.newProxyInstance会动态实现目标的接口,并调用代理的invoke方法,
54 //然后通过类加载器,动态的调用这个新生成的class并返回
55 diyProxy.buySomthin();
56 System.out.println("js笑了,我内牛满面了");
57 }
58
59 public static void main(String[] args){
60 Test t=new Test();
61 DIY diy=t.new DIYPC();
62 DIY diyProxy=(DIY)Proxy.newProxyInstance(diy.getClass().getClassLoader(), diy.getClass().getInterfaces(), t.new DIYHandler(diy));
63 JianShang(diyProxy);
64
65 }
66
67
68 }