代理模式(Proxy)
为其他对象提供一种代理机制以控制对这个对象的访问。
代理模式的应用
1) 远程代理:为一个对象在不同的地址空间提供代理,如WebService, Java RMI, Caucho Hessian
2) 虚拟代理:根据需要创建开销很大的对象,通过它来存放实例化需要很长时间的真实对象,如:Web代理服务器,反向代理Nginx, Squid
3) 其他代理:如控制真实对象的访问权限,计算真实对象的调用次数,记录日志、AOP事务处理等
一个简单的AOP事务处理代码(使用JDK动态代理实现)
- package test.gof.proxy;
- import test.gof.factory.Item;
- //商品服务
- public interface ItemService {
- int addItem(Item item);
- }
- package test.gof.proxy;
- import test.gof.factory.Item;
- import test.gof.factory.ItemDAO;
- import test.gof.factory.ItemDAOMySQLImpl;
- import test.gof.factory.UserDAO;
- import test.gof.factory.UserDAOMySQLImpl;
- //商品服务逻辑实现
- public class ItemServiceImpl implements ItemService {
- private ItemDAO itemDAO = new ItemDAOMySQLImpl();
- private UserDAO userDAO = new UserDAOMySQLImpl();
- @Override
- public int addItem(Item item) {
- //添加一个商品,同时更新用户的商品总数
- int result = itemDAO.insert(item);
- userDAO.updateItemCount(item.getUserId(), 1);
- return result;
- }
- public void setItemDAO(ItemDAO itemDAO) {
- this.itemDAO = itemDAO;
- }
- public void setUserDAO(UserDAO userDAO) {
- this.userDAO = userDAO;
- }
- }
- package test.gof.proxy;
- import java.lang.reflect.InvocationHandler;
- import java.lang.reflect.Method;
- //事务模板
- public class TransactionHandler implements InvocationHandler {
- private Object proxyObj;//被代理的对象
- @Override
- public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
- Object result = null;
- try {
- System.out.println("start transaction");
- result = method.invoke(proxyObj, args);
- System.out.println("commit transaction");
- } catch (Exception e) {
- System.out.println("rollback transaction");
- e.printStackTrace();
- }
- return result;
- }
- public void setProxyObj(Object proxyObj) {
- this.proxyObj = proxyObj;
- }
- }
- package test.gof.proxy;
- import java.io.File;
- import java.io.FileNotFoundException;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.lang.reflect.InvocationTargetException;
- import java.lang.reflect.Method;
- import java.lang.reflect.Proxy;
- import org.junit.Test;
- import sun.misc.ProxyGenerator;
- import test.gof.factory.Item;
- public class TestReflect {
- @Test
- public void testProxy() {
- Item item = new Item();
- item.setUserId(1);
- item.setItemName("hello kitty");
- ItemService proxy = (ItemService) this.getProxy(new ItemServiceImpl(), new TransactionHandler());
- proxy.addItem(item);
- }
- /**
- * @param proxyObj 代理对象
- * @param handler 事务模板
- * @return
- */
- public Object getProxy(Object proxyObj, TransactionHandler handler) {
- handler.setProxyObj(proxyObj);
- return Proxy.newProxyInstance(proxyObj.getClass().getClassLoader(), proxyObj.getClass().getInterfaces(), handler);
- }
- @SuppressWarnings("unchecked")
- @Test
- public void testProxyGenerator() {
- //生成的代理类文件,可以用jad反编译查看源码
- String proxyName = "ItemServiceProxy";
- ItemServiceImpl impl = new ItemServiceImpl();
- Class[] interfaces = impl.getClass().getInterfaces();
- byte[] proxyClassFile = ProxyGenerator.generateProxyClass(proxyName, interfaces);
- File file = new File("classes/ItemServiceProxy.class");
- try {
- FileOutputStream fos = new FileOutputStream(file);
- fos.write(proxyClassFile);
- fos.flush();
- fos.close();
- System.out.println("ItemServiceProxy: " + file.getAbsolutePath());
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- testProxy执行结果
- start transaction
- insert item to MySQL
- update itemCount to MySQL
- commit transaction