代理設計模式簡單例項
public interface Interface {
void doSomething();
void somethingElse(String arg);
}
public class RealObject implements Interface { public void doSomething() { System.out.println("RealObject.doSomething()"); } public void somethingElse(String arg) { System.out.println("RealObject.somethingElse("+arg+")"); } }
public class SimpleProxy implements Interface { private Interface proxied; public SimpleProxy(Interface proxied) { this.proxied = proxied; } public void doSomething() { System.out.println("SimpleProxy.doSomething()"); proxied.doSomething(); } public void somethingElse(String arg) { System.out.println("SimpleProxy.somethingElse("+arg+")"); proxied.somethingElse(arg); } }
/**
* 動態代理 簡單例項
*/
public class SimpleProxyDemo {
public static void consumer( Interface iface ) {
iface.doSomething();
iface.somethingElse("bonobo");
}
public static void main(String[] args) {
consumer(new RealObject());
consumer(new SimpleProxy(new RealObject()));
}
}