zoukankan      html  css  js  c++  java
  • 002设计模式 -- 代理模式

    1.uml

    2.抽象角色: 通过接口或抽象类声明真实角色实现的业务方法

    1 public interface Person {
    2     void sleep();
    3 
    4     void eat();
    5 }

    3.真实角色: 实现抽象角色, 定义真实角色所要实现的业务逻辑, 供代理角色调用

     1 public class Students implements Person {
     2     @Override
     3     public void sleep() {
     4         System.out.println("Students -- sleep");
     5     }
     6 
     7     @Override
     8     public void eat() {
     9         System.out.println("Students -- eat");
    10     }
    11 }
     1 public class Teacher implements Person {
     2     @Override
     3     public void sleep() {
     4         System.out.println("Teacher -- sleep");
     5     }
     6 
     7     @Override
     8     public void eat() {
     9         System.out.println("Teacher -- sleep");
    10     }
    11 }

    4.代理角色: 实现抽象角色, 是真实角色的代理, 通过真实角色的业务逻辑方法来实现抽象方法, 并可以附加自己的操作

     1 public class ProxyTest implements Person {
     2     private Person person;
     3 
     4     ProxyTest(Person person) {
     5         this.person = person;
     6     }
     7 
     8     @Override
     9     public void sleep() {
    10         this.person.sleep();
    11     }
    12 
    13     @Override
    14     public void eat() {
    15         this.person.eat();
    16     }
    17 }

    5.测试

     1 public class Test {
     2     public static void main(String[] args) {
     3         ProxyTest proxyTest;
     4         proxyTest = new ProxyTest(new Students());
     5         proxyTest.eat();
     6         proxyTest.sleep();
     7         System.out.println("==================================================");
     8         proxyTest = new ProxyTest(new Teacher());
     9         proxyTest.eat();
    10         proxyTest.sleep();
    11     }
    12 }

    6.结果

    7.总结

    7.1:优点

      >. 职责清晰: 真实的角色就是实现实际的业务逻辑, 不用关心其他非本职责的事务, 通过后期的代理完成一件完成事务, 附带的结果就是编程简洁清晰
      >. 代理对象可以在客户端和目标对象之间起到中介的作用, 这样起到了中介的作用和保护了目标对象的作用
      >. 高扩展性
  • 相关阅读:
    分布式文件系统 FastDFS
    Autoit里用多进程模拟多线程
    请不要做浮躁的人(新手必读!)
    如何用AU3调用自己用VC++写的dll函数
    DLL编写教程
    win32下的命令行集合 (最优秀的工具)
    autoit 《FAQ 大全》
    Windows XP 常用DOS命令
    rundll32 常用命令
    批处理的高级运用技巧
  • 原文地址:https://www.cnblogs.com/yanwu0527/p/8573490.html
Copyright © 2011-2022 走看看