本人在学习设计模式时总结的一点经验写出与大家一同分享:
其实代理模式是分两总代理,一种是静态代理,另一种是动态代理。静态代理是先声明一个接口,然后用一个类实现这个接口。然后新建另一个类也实现这个接口,在这个类中声明一个属性引用前一个类。在实在方法时做你想做的事,然后在运行前一个类实现的方法。
package org.jms.beans.test;
public interface ComputerInterface {
void computerFunction();
}
package org.jms.beans.test;
public class PrintFunction implements ComputerInterface {
public void computerFunction() {
// TODO Auto-generated method stub
System.out.println("计算机有打印功能。");
}
}
package org.jms.beans.test;
public class ProxyComputerFunction implements ComputerInterface {
private ComputerInterface printfunction ;
public ComputerInterface getPrintfunction() {
return printfunction;
}
public void setPrintfunction(ComputerInterface printfunction) {
this.printfunction = printfunction;
}
public void computerFunction() {
// TODO Auto-generated method stub
System.out.println("先把打印机打开..");
printfunction.computerFunction();
}
}
建一个测试类
package org.jms.beans.test;
public class ProxyTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ProxyComputerFunction proxyComputerFunction = new ProxyComputerFunction();
proxyComputerFunction.setPrintfunction(new PrintFunction());
proxyComputerFunction.computerFunction();
}
}
动态代理则是实现 InvocationHandler 这个接口,在这个实现类中绑定一个对象。
package org.jms.beans.test;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class DyProxy implements InvocationHandler {
Object delegate ;
public Object bind(Object delegate){
this.delegate = delegate ;
return Proxy.newProxyInstance(delegate.getClass().getClassLoader(), delegate.getClass().getInterfaces(), this);
}
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
// TODO Auto-generated method stub
System.out.println("先把打印机打开...");
return method.invoke(delegate, args);
}
}
测试一下
package org.jms.beans.test;
public class ProxyTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
DyProxy dyProxy = new DyProxy();
ComputerInterface computer = (ComputerInterface) dyProxy.bind(new PrintFunction());
computer.computerFunction() ;
}
}