代理模式

一、静态代理

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

	public 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("代理类开始执行!");
	  cf.productCloth();	
	}
	
}


public class TestClothFactory{
	
	public static void main(String[] args) {
		NikeClothFactory nike=new NikeClothFactory();//创建被代理对象
		ProxyFactory proxy=new ProxyFactory(nike);//创建代理类的对象
		proxy.productCloth();
	}
}

二、动态代理

//动态代理的使用,反射是动态语言的关键
interface Subject{
	public 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 {
		//method方法的返回值是returnVal
		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();
		//3、调用blind方法,动态的返回一个同样实现了real所在类实现的接口的代理类的对象 
		Object obj=handler.blind(real);
		Subject sub=(Subject)obj;//此时sub就是代理类对象
		//4、
		sub.action();//转到对InvocationHandler接口的实现类Invoke方法的调用 
		//
		NikeClothFactory nike=new NikeClothFactory();//创建被代理对象
		ClothFactory proxyCloth=(ClothFactory) handler.blind(nike);
		proxyCloth.productCloth();
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值