Proxy模式
为其他对象提供一种代理以控制对这个对象的访问等
Service.java
package com.gary.designpattern.proxy;/** * 定义公用接口,这样使用RealService的地方都可以使用Proxy * @author gary * */public interface Service {public void sayHello();}
?
RealService.java
package com.gary.designpattern.proxy;/** * 代理对象 * @author gary * */public class RealService implements Service{@Overridepublic void sayHello() {System.out.println("Hello World!");}}
?
Proxy.java
package com.gary.designpattern.proxy;/** * 代理,实现Service接口,来代替代理对象 * @author gary * */public class Proxy implements Service{//使代理可以访问代理的对象private RealService rs = new RealService();@Overridepublic void sayHello() {System.out.println("do something before sayHello");rs.sayHello();System.out.println("do something after sayHello");}}
?
Test.java
package com.gary.designpattern.proxy;/** * 测试 * @author gary * */public class Test {public static void main(String[] args) {Service proxy = new Proxy();proxy.sayHello();}}
?