JAVA靜態代理與動態代理

代理模式:客戶-->經紀人-->歌星
            |        |  |
           客戶-->代理類-->委託類
  上面將生活中的角色一一對應成java的類
  歌星開演唱會的步驟:宣傳-->售票-->唱歌-->收尾款
 
分類有兩種
1.靜態代理
現實生活中: 一個歌星可能要開好幾場演唱會,導致忙不過來,所以聘請一個代理,幫組他完成唱歌以外的所有步驟,歌星本人只負責唱歌就行
 程序設計中: 定義一個接口,裏面只定義開演唱會的唱歌方法,然後定義一個明星類和一個代理明星類,這兩個類都實現了此接口,然後重寫接口
的方法,在代理類裏面重寫唱歌的方法時,方法體裏面直接調用歌星類的唱歌方法,,歌星類重寫唱歌的時候,方法體就寫具體唱
歌內容,前提是代理類裏面必須持有一個歌星類的引用
例如: interface ImI{void sing();}//聲明接口
//定義一個代理類相當於經紀人
class proxy implements ImI(){
Star star;
public proxy(Star star){this.star=star;}//持有委託類的引用
void show(){System.out.println("show");}
void sale(){System.out.println("saleticket");}
public void sing(){star.sing();}
void recivept(){System.out.println("recivept");}

}
//定義一個委託類相當於明星
class Star implements ImI{
public void sing(System.out.println("sing...."));
}
//定義一個測試類,相當於客戶
class Test{
Star star=new Star();//構造一個委託類的對象
Proxy proxy=new Proxy(star);//構造一個代理類的對象,並將委託類的對象作爲實參傳入
proxy.show();
proxy.sale();
proxy.sing();
proxy.recivept();
}

2.動態代理

 : 由於靜態代理裏面的代理類寫死了,不夠靈活,不能夠滿足生活中的需求,

例如房屋中介,代理的肯定不止一家僱主的房子,而是根據客戶需求需要哪一套房子,然後去找房子的主人,
程序設計中:
interface ImI{void sing();}//聲明接口
//定義一個委託類相當於明星
class Star implements ImI{
public void sing(System.out.println("sing...."));
}
//定義一個程序處理器,並實現InvcationHandler接口
calss Handler implements InvocationHanlder{
Star target;
public Handler(Star star){
this.target=star;
}
//重寫InvocationHandler的invoke方法
public Object invoke(Object proxy,Method method,object[] args){
method.invoke(target,args);
return null;
}
public Object newInstance(){
Class c=target.getClass();
return Proxy.newProxynewInstance(c.getClassLoader,c.getInterfaces()||new Class[]{ImI.class}),target);
}
}
//定義一個測試類
class Test{
public static void main(String args[]){
Star star=new Star();
Handler handler=new Handler(star);//此處可以傳入任意一個委託類,並也不侷限於Star 這就是動態代理的根本體現
ImI proxy=handler.newInstance();//1

Class cls=Proxy.getProxyClass(star.getClass().getClassLoader(),star.getClass*().getInterfaces());//2.生成代理類
Constructor constructor=cls.getConstructor(new Class[]{InvocationHandler.class});//3.獲取代理類的構造函數
ImI proxy=(ImI)constructor.newInstance(new Object[]{handler});//4.利用構造函數構造一個代理類的對象

備註:1=2+3+4; //寫了1之後就註釋掉234,謝寫了234就註釋掉1
proxy.sing();
}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章