标签:des style class blog code java
1. 概念
代理模式又称为委托模式 ;为其他对象提供一种代理以控制对这个对象的访问。
2. 案例
package org.demo.proxy.demo01; public class Demo03 { public static void main(String[] args) { IUser user = new UserProxy(new UserImpl()) ; user.action() ; } } interface IUser{ void action() ; } class UserImpl implements IUser{ @Override public void action() { System.out.println("被代理的对象"); } } class UserProxy implements IUser{ private IUser user ; public UserProxy(IUser user) { this.user = user ; } @Override public void action() { System.out.println("调用被代理对象"); user.action() ; } }
结果:
调用被代理对象
被代理的对象
JDK动态代理
/********************************************************************** * <pre> * FILE : Demo02.java * CLASS : Demo02 * * AUTHOR : Liaokailin * * FUNCTION : TODO * * *====================================================================== * CHANGE HISTORY LOG *---------------------------------------------------------------------- * MOD. NO.| DATE | NAME | REASON | CHANGE REQ. *---------------------------------------------------------------------- * |2014-3-7|Liaokailin| Created | * DESCRIPTION: * </pre> ***********************************************************************/ package org.demo.proxy.demo01; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; public class Demo02 { /** * Function : * @author : Liaokailin * CreateDate : 2014-3-7 * version : 1.0 * @param args */ public static void main(String[] args) { Foo prox = (Foo)Proxy.newProxyInstance(Demo01.class.getClassLoader(), new Class[]{Foo.class}, new InvocationHandler(){ @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println(args[0]) ; System.out.println( method.getName()) ; return null; }}) ; prox.f("Helll World") ; } } interface Foo{ void f(String s) ; void g(int i) ; }
结果:
Helll World
f
标签:des style class blog code java
原文地址:http://www.cnblogs.com/liaokailin/p/3800007.html