当前位置: 首页 > 图文教程 > 网络编程 > PHP > PHP设计模式-对象行为型模式-VISITOR

PHP
利用客户端缓存对网站进行优化的原理分析
php生成随机数或者字符串的代码
php include,include_once,require,require_once
php 特殊字符处理函数
php让图片可以下载的代码
网友原创的PHP模板类代码
wiki-shan写的php在线加密的解密程序
php chr() ord()中文截取乱码问题解决方法
php+AJAX传送中文会导致乱码的问题的解决方法
php面向对象的方法重载两种版本比较
在服务端进行目录建立、删除,文件上传、删除的过程的php代码
php递归列出所有文件和目录的代码
php获取某个目录大小的代码
php目录管理函数小结
Zend Guard一些常见问题解答
fleaphp下不确定的多条件查询的巧妙解决方法
PHP下10件你也许并不了解的事情
PHP常用函数小技巧
php5 pdo新改动加载注意事项
php5新改动之短标记启用方法

PHP设计模式-对象行为型模式-VISITOR


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-11-03   浏览: 176 ::
收藏到网摘: n/a

    个人认为在23个经典模式中VISITOR是比较难理解的一个,所以决定先讲讲自己对VISITOR的理解。因为马哲认为对事物的认识是从具体到抽象的一个过程,所以在谈理论之前先说一个例子是必要的。这个例子不是实际应用,但我想它还算生动,是个记忆VISITOR模式的好例子吧。

    英国、美国都有自己的核武机构,每个国家的核武机构,都使用不同的接口来进行通讯:

CODE:
    class Country
    {
         // ...
    }
   

1,对于英国,核武密码被分成三个部分,需要用三个接口取得:
CODE:
   interface I1{function get1();};
   interface I2{function get2();};
   interface I3{function get3();};
   class English extends Country implements I1,I2,I3
   {
               function get1(){return '123';}
               function get2(){return '456';}
               function get3(){return '789';}
   }
   

2,对于美国,保管核武密码的方式不一样,使用了5个接口来分别取得密码的部分:
CODE:
   interface Ia{function getA();};
   interface Ib{function getB();};
   interface Ic{function getC();};
   interface Id{function getD();};
   interface Ie{function getE();};
   class America extends Country implements Ia,Ib,Ic,Id,Ie
   {
               function getA(){return 'a';}
               function getB(){return 'b';}
               function getC(){return 'c';}
               function getD(){return 'd';}
               function getE(){return 'e';}
   }
   

如果我们中国欲取得此二国的核武密码,则必须先熟知这二国的核武密码接口。实际行动(runtime)时,
用if..else来判断现在具体是哪个国家,然后调用该国相应的核武密码接口。
CODE:
      class Client
      {
            private function getRealPwd(Country $country)
            {
                  if($country instanceof English)
                  {
                      return $country->get1() mod ( $country->get2() + $country->get3() );
                  }elseif($country instanceof American){
                        return $country->getA() . $country->getB() . $country->getC() . $country->getD() . $country->getE();
                  }elseif(...){
                        ...
                  }
            }
      }