0
点赞
收藏
分享

微信扫一扫

动态代理---例子


动态代理类的实例

interface Subject {

void action();
}

// 被代理类

class RealSubject implements Subject {

@Override
public void action() {
System.out.println("我是被代理类,记得要执行我哦!么么~~");
}

}

class MyInvocationHandler implements InvocationHandler {

// 实现了接口的被代理类的对象的声明
Object obj;

// ①给被代理类的对象实例化 ②返回一个代理类的对象
public Object blind(Object obj) {
this.obj = obj;
return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), this);
}


//当通过代理类的对象发起对被重写的方法的调用时,都会转化为对如下的invoke方法的调用
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

Object returnval = method.invoke(obj, args);
return returnval;
}

}

public class TestProxy {

public static void main(String[] args) {

//1.被代理类的对象
RealSubject real = new RealSubject();
//2.创建一个实现了InvocationHandler接口的类的对象
MyInvocationHandler handler = new MyInvocationHandler();

//调用blind()方法,动态的返回一个同样实现了real所在类实现的接口Subject的代理类的对象
Object obj = handler.blind(real);
//此时的sub就是代理类的对象
Subject sub = (Subject) obj;

sub.action();//转到对InvocationHandler接口的实现类的invoke()方法来调用



//再举一例

//通过调用静态代理类来说明此方法时懂爱的

NikeClothFactory nike = new NikeClothFactory();
//proxyCloth即为代理类的对象
ClothFactory proxyCloth = (ClothFactory) handler.blind(nike);
proxyCloth.productCloth();
}
}

静态代理类:

package proxy;


/**
*静态代理模式
*接口
*/
interface ClothFactory{

void productCloth();
}

//被代理类
class NikeClothFactory implements ClothFactory{

@Override
public void productCloth() {
System.out.println("Nike工厂生产一批衣服");
}

}


//代理类
class ProxyFactory implements ClothFactory{

ClothFactory cf;
//创建代理类的对象时,实际传入一个被代理类的对象
public ProxyFactory(ClothFactory cf){
this.cf = cf;
}

@Override
public void productCloth() {
System.out.println("代理类开始执行,收代理费$1000");
cf.productCloth();
}

}


public class TestClothProduct {

public static void main(String[] args) {

//创建被代理类的对象
NikeClothFactory nike = new NikeClothFactory();

//创建代理类的对象
ProxyFactory proxy = new ProxyFactory(nike);
proxy.productCloth();
}

}


举报

相关推荐

0 条评论