生活随笔
收集整理的這篇文章主要介紹了
                                
动态代理-JDK
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.                        
 
                                
                            
                            
                            代理模式:假設一個場景,你的公司是一位軟件公司,你是一位軟件工程師,顯然客戶帶著需求不會去找你談,而是去找商務談,此時商務就代表公司。
 商務的作用:商務可以談判;也有可能在開發軟件之前就談失敗,此時商務就會根據公司規則去結束和客戶的關系,這些都不用軟件工程師來處理。
 代理對象的作用:在真實對象訪問之前或者之后加入對應的邏輯,或者根據其他控制是否使用真實對象,這個例子就是商務控制了客戶對軟件工程師的訪問。客戶就是程序中的調用者,商務就是代理對象,軟件工程師就是真是對象
 1.定義接口
 
public interface HelloWorld {public void sayHelloWorld();
} 
2.創建實現類實現接口
 
package cn
.batis
.impl
;import cn
.batis
.interfaces
.HelloWorld
;public class HelloWorldImpl implements HelloWorld {public void sayHelloWorld() {System
.out
.println("hello world!");}
} 
3.建立代理對象和真實對象之間的關系(bind方法)
 4.實現代理邏輯方法(invoke方法)
 
package cn
.batis
.proxy
;import java
.lang
.reflect
.InvocationHandler
;
import java
.lang
.reflect
.Method
;
import java
.lang
.reflect
.Proxy
;public class JDKProxyExample implements InvocationHandler {private Object target
=null
;public Object 
bind(Object target
){this.target
=target
;return Proxy
.newProxyInstance(target
.getClass().getClassLoader(),target
.getClass().getInterfaces(),this);}public Object 
invoke(Object proxy
, Method method
, Object
[] args
) throws Throwable 
{System
.out
.println("進入代理邏輯方法");System
.out
.println("在調度真實對象之前的服務");Object obj 
= method
.invoke(target
, args
);System
.out
.println("在調度真實對象之后的服務");return obj
;}
}
                            總結
                            
                                以上是生活随笔為你收集整理的动态代理-JDK的全部內容,希望文章能夠幫你解決所遇到的問題。
                            
                            
                                如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。