设计模式之代理模式

JDK动态代理

1、被代理的类必须实现一个接口
2、创建代理对象的时候,用JDK代理需要实现InvocationHandler
3、代理过程在invoke中实现

接口

public interface LandlordService {
	void rentingPay(String name);
}

被代理对象

public class Landlord implements LandlordService{
	/****
	* @param name
	*/
	@Override
	public void rentingPay(String name){
		System.out.println(name+" 来交租!");
	}
}

代理对象

public class QFangProxy implements InvocationHandler{
	private Object instance;
	public QFangProxy(Object instance) {
		this.instance = instance;
	} 
	/****
	* 代理过程
	* @throws Throwable
	*/
	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		args[0] = "中介QFang带领租户"+args[0];
		Object result = method.invoke(instance, args);
		return result;
	}
}

测试

public class JdkProxyTest {
	public static void main(String[] args) {
		//给QFang产生代理
		LandlordService landlordService = new Landlord();
		QFangProxy proxy = new QFangProxy(landlordService);
		LandlordService landlordServiceProxy = (LandlordService)
		Proxy.newProxyInstance(LandlordService.class.getClassLoader(), new Class[]
		{LandlordService.class}, proxy);
		//通过代理对象调用Landlord对象的方法
		landlordServiceProxy.rentingPay("王五");
	}
}

CGLib动态代理

要点:
1、代理过程可以实现MethodInterceptor(Callback)接口中的invoke来实现
2、通过Enhancer来创建代理对象

被代理类基于上方提供

代理类

public class SFangProxy implements MethodInterceptor {
	private Object instance;
	public SFangProxy(Object instance) {
		this.instance = instance;
	} /
	***
	* 代理过程
	* @throws Throwable
	*/
	@Override
	public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy)throws Throwable {
		args[0]="S房网带租户"+args[0];
		return method.invoke(instance,args);
	}
}

基于接口

public class CGLibProxyTest {
	public static void main(String[] args) {
		//给QFang产生代理
		LandlordService landlordService = new Landlord();
		SFangProxy proxy = new SFangProxy(landlordService);
		LandlordService landlordServiceProxy = (LandlordService)
		Enhancer.create(LandlordService.class,proxy);
		//通过代理对象调用Landlord对象的方法
		landlordServiceProxy.rentingPay("王五");
	}
}

基于类

public class CGLibProxyTest {

    public static void main(String[] args) {
        //给指定对象创建代理
        Landlord landlord = new Landlord();

        //1.被代理的对象字节码
        //2.代理的过程实现,需要实现接口MethodInterceptor->Callback
        Landlord proxyLandlord = (Landlord) Enhancer.create(Landlord.class,new SFang(landlord));
        proxyLandlord.pay("赵六");
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值