Java的Proxy,一种思考和解决问题的方法

静态代理

在不破坏原有功能的情况下,进行升级改造。
使用场景,通常在旧项目改造和升级中,不能或者没有条件在源码的基础上升级和改造
所以用代理模式是一个不错的选择。

功能列表(接口)

public interface IDoing {
	public String doFirst();
	public void doSecond();
}

原有功能,功能的实现

@Slf4j
public class DoingImpl implements IDoing {
	@Override
	public String doFirst() {
		String me = "Hi there,this is Michael";
		return me;
	}
	
	@Override
	public void doSecond() {
		log.info("let's started now");
	}
}

在不破坏原功能的情况下Enhance

public class DoingProxy implements IDoing {

	private IDoing idoing;
	
	DoingProxy(){
		this.idoing = new DoingImpl();
	}
	@Override
	public String doFirst() {
		return idoing.doFirst().toUpperCase();
	}
	@Override
	public void doSecond() {
		idoing.doSecond();
	}
}

Test

@Slf4j
public class TestProxy {
	public static void main(String[] args) {
		IDoing idoing = new DoingImpl();
		IDoing idoing = new DoingProxy();
		log.info(idoing.doFirst());
		idoing.doSecond();
	}
}

Hi there,this is Michael
HI THERE,THIS IS MICHAEL
let’s started now

JDK 动态代理

在静态代理的基础上改造

@Slf4j
public class TestProxy {
	public static void main(String[] args) {
		IDoing target = new DoingImpl();
		IDoing proxyIdoing = (IDoing) Proxy.newProxyInstance(
				target.getClass().getClassLoader(), 
				target.getClass().getInterfaces(),
				new InvocationHandler() {
					@Override
					public Object invoke(
						Object proxy, 
						Method method, 
						Object[] args) throws Throwable {
						Object result = method.invoke(target, args);
						if (result!=null) {
							result = result.toString().toUpperCase();
						}
						return result;
					}
					
				} );
		
		String doFirst = proxyIdoing.doFirst();
		log.info(doFirst);
		proxyIdoing.doSecond();
	}
}

Cglib 代理模式

Callback的MethodInterceptor

public interface MethodInterceptor extends Callback

public class CglibProxyEnhancer implements MethodInterceptor {
	public DoingImpl getCglibCreator() {
		Enhancer enhancer = new Enhancer();
		enhancer.setSuperclass(DoingImpl.class);
		enhancer.setCallback(this);
		return (DoingImpl) enhancer.create();
	}
	
	@Override
	public Object intercept(
		Object obj, 
		Method method, 
		Object[] args,
		MethodProxy proxy) throws Throwable {
		Object result = method.invoke(new DoingImpl(), args);
		if (result!=null) {
			result = result.toString().toUpperCase();
		}
		return result;
	}
}

test

@Slf4j
public class TestProxy {

	public static void main(String[] args) {
		 
		CglibProxyEnhancer cglibProxyEnhancer = new CglibProxyEnhancer();
		DoingImpl proxyIdoing = cglibProxyEnhancer.getCglibCreator();
		
		String doFirst = proxyIdoing.doFirst();
		
		log.info(doFirst);
		proxyIdoing.doSecond();
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值