比如要在輸出
A:先定義一個接口類
Java代碼
package ttitfly
public interface HelloWorld {
public void print();
// public void say();
}
package ttitfly
public interface HelloWorld {
public void print();
// public void say();
}
B: 定義一個該接口的實現類
Java代碼
package ttitfly
public class HelloWorldImpl implements HelloWorld{
public void print(){
System
}
// public void say(){
// System
// }
}
package ttitfly
public class HelloWorldImpl implements HelloWorld{
public void print(){
System
}
// public void say(){
// System
// }
}
C:定義一個靜態代理類
Java代碼
package ttitfly
public class StaticProxy implements HelloWorld{
public HelloWorld helloWorld ;
public StaticProxy(HelloWorld helloWorld){
this
}
public void print(){
System
//相當於回調
helloWorld
}
// public void say(){
// //相當於回調
// helloWorld
// }
}
package ttitfly
public class StaticProxy implements HelloWorld{
public HelloWorld helloWorld ;
public StaticProxy(HelloWorld helloWorld){
this
}
public void print(){
System
//相當於回調
helloWorld
}
// public void say(){
// //相當於回調
// helloWorld
// }
}
D: 一個測試類:
Java代碼
package ttitfly
public class TestStaticProxy {
public static void main(String[] args){
HelloWorld helloWorld = new HelloWorldImpl();
StaticProxy staticProxy = new StaticProxy(helloWorld);
staticProxy
// staticProxy
}
}
package ttitfly
public class TestStaticProxy {
public static void main(String[] args){
HelloWorld helloWorld = new HelloWorldImpl();
StaticProxy staticProxy = new StaticProxy(helloWorld);
staticProxy
// staticProxy
}
}
可以看出靜態代理類有一個很不爽的缺點
動態代理與普通的代理相比較
動態代理類只能代理接口
代理類
Java代碼
package ttitfly
import java
import java
import java
//動態代理類只能代理接口
public class DynamicProxy implements InvocationHandler{
private Object object;
//綁定關系
//Proxy
public Object bindRelation(Object object){
this
return Proxy
}
//攔截關聯的這個實現類的方法被調用時將被執行
public Object invoke(Object proxy
System
Object result = method
return result;
}
}
package ttitfly
import java
import java
import java
//動態代理類只能代理接口
public class DynamicProxy implements InvocationHandler{
private Object object;
//綁定關系
//Proxy
public Object bindRelation(Object object){
this
return Proxy
}
//攔截關聯的這個實現類的方法被調用時將被執行
public Object invoke(Object proxy
System
Object result = method
return result;
}
}
測試類
Java代碼
package ttitfly
public class TestDynamicProxy {
public static void main(String[] args){
HelloWorld helloWorld = new HelloWorldImpl();
DynamicProxy dp = new DynamicProxy();
//在這裡綁定的是HelloWorld
HelloWorld helloWorld
helloWorld
helloWorld
//helloWorld
HelloWorld helloWorld
helloWorld
helloWorld
}
}
package ttitfly
public class TestDynamicProxy {
public static void main(String[] args){
HelloWorld helloWorld = new HelloWorldImpl();
DynamicProxy dp = new DynamicProxy();
//在這裡綁定的是HelloWorld
HelloWorld helloWorld
helloWorld
helloWorld
//helloWorld
HelloWorld helloWorld
helloWorld
helloWorld
}
}
在測試類裡調用實現類的print和say方法
總結
動態代理類
代理類可以為委托類預處理消息
From:http://tw.wingwit.com/Article/program/Java/hx/201311/25797.html