码迷,mamicode.com
首页 > 其他好文 > 详细

代理模式之动态代理

时间:2014-10-27 15:42:35      阅读:179      评论:0      收藏:0      [点我收藏+]

标签:java   设计模式   代理模式   动态代理   

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;


//接口
interface MyInterface {
	public void action();
}

// 被代理类
class MyObject implements MyInterface {
	@Override
	public void action() {
		System.out.println("我是被代理类,执行action!");
	}
}

//被代理接口
interface ClothFactory{
	public void productCloth();
}

//被代理类
class NikeClothFactory implements ClothFactory{

	@Override
	public void productCloth() {
		System.out.println("我是被代理类,Nike 生产衣服");
	}
}

//实现InvocationHandler接口的子类
class MyInvocationhandler implements InvocationHandler {

	private Object obj;

	public void setObject(Object obj) {
		this.obj = obj;
	}

	@Override
	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		System.out.println("动态代理类执行,收代理费");
		Object returnVal = method.invoke(obj, args);
		return returnVal;
	}

}

//动态代理类
class MyProxy {

	public static Object getProxyInstance(Object obj, InvocationHandler handler) {
		return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj
				.getClass().getInterfaces(), handler);
	}
}

public class TestProxy {

	/**
	 * @Title: main
	 * @Description:
	 * @param:
	 * @return void
	 * @user: wangzg
	 * @Date:2014-10-27
	 * @throws
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		//被代理类
		MyObject myObject = new MyObject();
		
		MyInvocationhandler myInvocationhandler = new MyInvocationhandler();
		myInvocationhandler.setObject(myObject);
		Object myProxy =  MyProxy.getProxyInstance(myObject, myInvocationhandler);
		MyInterface myInterface = (MyInterface)myProxy;
		myInterface.action();
		
		
		NikeClothFactory nikeClothFactory = new NikeClothFactory();
		myInvocationhandler.setObject(nikeClothFactory);
		Object myProxyNike =  MyProxy.getProxyInstance(nikeClothFactory, myInvocationhandler);
		ClothFactory clothFactory = (ClothFactory)myProxyNike;
		clothFactory.productCloth();
	}

}

代理模式之动态代理

标签:java   设计模式   代理模式   动态代理   

原文地址:http://blog.csdn.net/sd_tz_wzg/article/details/40507167

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!