/** * */ package typeinfo; /** * 简单代理模式的使用。 * 代理模式提供了隐藏和扩展的能力,将被代理者可以隐藏起来,而且可以在代理类中对被代理的 * 功能再进行加工包装,使其更丰满。 * */ /** * 定义出代理对象的接口 * @author LYL * */ interface Interface{ void doSomething(); void somethingElse(String arg); } /** * 被代理的对象,是真正干活的 * @author LYL * */ class RealObject implements Interface{ @Override public void doSomething() { System.out.println("RealObject doSomething"); } @Override public void somethingElse(String arg) { System.out.println("RealObject somethingElse"+arg); } } /** * 代理类,同样实现了Interface接口,但是只是一个代理,真正干活是另有其人。 * 代理类只是起到一个中间角色,起到白手套的作用。 * @author LYL * */ class SimpleProxy implements Interface { private Interface proxied; //被代理者 public SimpleProxy(Interface proxied){ this.proxied=proxied; } @Override public void doSomething() { //除了代理以外,还可以附加一些其它的服务 System.out.println("SimpleProxyDemo doSomething."); //将工作转给被代理的来做 this.proxied.doSomething(); } @Override public void somethingElse(String arg) { System.out.println("SimpleProxyDemo somethingElse "+arg); this.proxied.somethingElse(arg); } } /** * 简单代理类测试 * @author LYL * */ public class SimpleProxyDemo{ public static void consumer(Interface iface){ iface.doSomething(); iface.somethingElse(" invoke "); } public static void main(String args[]) throws Exception{ //直接使用类 System.out.println("直接使用类"); consumer(new RealObject()); //通过代理来使用被代理的类 System.out.println("通过代理来使用被代理的类"); consumer(new SimpleProxy(new RealObject())); } }