代理模式结构图

image.png
代码

  1. public class ProxyTest {
  2. public static void main(String[] args) {
  3. Proxy proxy = new Proxy();
  4. proxy.Request();
  5. }
  6. }
  7. //抽象类
  8. public abstract class Subject {
  9. public abstract void Request();
  10. }
  11. //被代理的对象
  12. public class RealSubject extends Subject{
  13. @Override
  14. public void Request() {
  15. System.out.println("真实的请求");
  16. }
  17. }
  18. //代理对象
  19. public class Proxy extends Subject{
  20. Subject subject;
  21. @Override
  22. public void Request() {
  23. if (subject == null){
  24. subject = new RealSubject();
  25. }
  26. System.out.println("代理方法");
  27. subject.Request();
  28. }
  29. }