首页 > 代码库 > 设计模式 -- 代理模式 (proxy Pattern)

设计模式 -- 代理模式 (proxy Pattern)

定义:

为其他对象提供一种代理以控制对这个对象的访问;

角色:

1,抽象主题类,(接口或者抽象类),抽象真实主题和代理的共有方法(如下Subject类);

2,具体实现的主题类,继承或者实现抽象主题类的抽象方法(如下RealSubject类);

3,代理类,继承实现抽象主题类,并提供传递具体实现主题类,在实现方法里面调用具体实现的主题类(如下ProxySubject类);

Subject.java

/** * Created by Administrator on 2016/8/31. */public abstract class Subject {    public abstract void visit();}

RealSubject.java

/** * Created by Administrator on 2016/8/31. */public class RealSubject extends Subject {    @Override    public void visit() {        System.out.print("RealSubject实现visit方法");    }}

代理类ProxySubject.java :

/** * Created by Administrator on 2016/8/31. */public class ProxySubject extends Subject {    private RealSubject realSubject;    public ProxySubject(RealSubject realSubject) {        this.realSubject = realSubject;    }    @Override    public void visit() {        realSubject.visit();    }}

测试类:

/** * Created by Administrator on 2016/8/31. */public class Test {    public static void main(String[] args) {        RealSubject RealSubject = new RealSubject();        ProxySubject ProxySubject = new ProxySubject(RealSubject);        ProxySubject.visit();    }}

运行结果:

RealSubject实现visit方法

 如上为静态代理,还有通过反射来实现的动态代理:

动态代理类:DynamicProxy.java 

public class DynamicProxy implements InvocationHandler {    private Object object;    public DynamicProxy(Object object) {        this.object = object;    }    @Override    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {        Object result = method.invoke(object, args);        return result;    }}

 

设计模式 -- 代理模式 (proxy Pattern)