静态代理:每个代理类只为一个接口服务
动态代理:指客户通过代理类来调用其他对象的方法,并且是在程序运行时根据需要动态创建目标类
//静态代理代码:
package itheima;
import java.lang.reflect.*;
import java.util.*;
public class apple {
/**
* @param args
*/
public static void main(String[] args) throws Exception{
NikeClothFactory nike=new NikeClothFactory();
ProxyFactory proxy=new ProxyFactory(nike);
proxy.productCloth();
}
}
//接口
interface ClothFactory{
void productCloth();
}
//被代理类
class NikeClothFactory implements ClothFactory {
public void productCloth(){
System.out.println("NiKe工厂生产一批衣服");
}
}
//代理类
class ProxyFactory implements ClothFactory{
ClothFactory cf;
public ProxyFactory(ClothFactory cf){
this.cf=cf;
}
public void productCloth() {
// TODO Auto-generated method stub
System.out.println("代理类开始执行,收代理费100");
cf.productCloth();
}
}
//动态代理代码
import java.lang.reflect.*;
//动态代理接口
interface Subject{
void action();
}
//被代理类
class RealSubject implements Subject
{
public void action()
{
System.out.println("我是被代理类,我来了");
}
}
class MyInvocationHandler implements InvocationHandler {
Object obj;//实现了接口的被代理类声明
public Object bind(Object obj)
{
this.obj=obj;
return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), this);
}
public Object invoke(Object proxy,Method method,Object[] args)throws Throwable{
Object returnVal=method.invoke(obj, args);
return returnVal;
}
}
class apple1{
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
//1.被代理类的对象
RealSubject real=new RealSubject();
//2.创建了一个实现了InvacationHandler接口的类的对象
MyInvocationHandler handler=new MyInvocationHandler();
//3.调用bind()方法,动态的返回一个同样实现了real所在类实现的接口Subject的代理对象
Object obj=handler.bind(real);
Subject sub=(Subject)obj;//此时的sub为代理类的对象
//4.转到对InvacationHandler接口实现类的invoke()方法调用
sub.action();
NikeClothFactory nike=new NikeClothFactory();
}
}
|
|