设计模式|代理模式

代理模式:为其他对象提供一种代理以控制对这个对象的访问。

静态代理的关键:代理类(SubjectProxy)实现被代理类的接口(ISubject)。

类结构

             +-------------+
             |             |
             |    ISubject interface
             |             |
             +-^---------^-+
               |         |
          implement      |implement
               |         |
               |         |
+--------------+-+      ++--------------+
|                |      |               |
|  SubjectProxy  |      |  Subject      |
+----------------+      +---------------+

代码

public interface ISubject {
    void request();
}
public class Subject implements ISubject {
    @Override
    public void request() {
        System.out.println("Subject的request方法执行了.");
    }
}
public class SubjectProxy implements ISubject {
    private ISubject subject = new Subject();

    @Override
    public void request() {
        System.out.println("代理类SubjectProxy的request方法执行了.");
        subject.request();
    }
}
public class Main {
    public static void main(String[] args) {
        SubjectProxy subjectProxy = new SubjectProxy();
        subjectProxy.request();

    }
}