设计模式之代理模式

2018-02-27 10:51:13 浏览数 (2)

       代理模式是一种注重过程的一种模式,在我们做某一具体事情之前或之后做一些辅助性的工作; 好处是将辅助工作从主要工作中抽离出来,但是又能协同工作, 我们只关心主要业务,对于不关心的事情交给代理来做,实现代理需要两个对象:被代理者,执行者

JDK中提供的动态代理(只能代理接口): 

代码语言:javascript复制
public interface IBuy {
	void pay();
}

public class Buy implements IBuy{

	@Override
    public void pay() {
	    System.out.println("订单支付完成!");
    }

public class PayProxy implements InvocationHandler {
	private Object obj;
	public PayProxy(Object target) {
	   this.obj = target;
    }

	public Object newInstance() {
		Class<? extends Object> cls = obj.getClass();
		return Proxy.newProxyInstance(cls.getClassLoader(), cls.getInterfaces(), this);
	}
	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		Object res = method.invoke(obj, args);
		System.out.println("----------");
		sendMsg();
		return res;
	}
	
	private void sendMsg(){
		System.out.println("买家已付款,请尽快发货!");
	}
}

--------------
IBuy buy = (IBuy)new PayProxy(new Buy()).newInstance();
		buy.pay();


console:
订单支付完成!
----------
买家已付款,请尽快发货!

CGLIB方式(代理具体类):

代码语言:javascript复制
public class Buy{
    public void pay() {
	    System.out.println("订单支付完成!");
    }

}

public class CglibPayProxy implements MethodInterceptor {
	private static final CglibPayProxy PROXY = new CglibPayProxy();
	private CglibPayProxy() {
	}

	public static CglibPayProxy getInstance() {
		return PROXY;
	}

	@SuppressWarnings("unchecked")
	public <T> T newProxy(Class<T> clazz) {
		Enhancer enhancer = new Enhancer();
		 enhancer.setSuperclass(clazz);
		 enhancer.setCallback(this);
		 return (T) enhancer.create();
	}

	@Override
	public Object intercept(Object arg0, Method arg1, Object[] arg2, MethodProxy arg3)
	        throws Throwable {
		Object res = arg3.invokeSuper(arg0, arg2);
		System.out.println("------------");
		sendMsg();
		return res;
	}

	private void sendMsg() {
		System.out.println("买家已付款,请尽快发货!");
	}


Buy buy = CglibPayProxy.getInstance().newProxy(Buy.class);
		buy.pay();

0 人点赞