终于搞定,累成一滩,今晚不想说话。

<?php
/*
The visitor design pattern is a way of separating an algorithm from an object
structure on which it operates. As a result, we are able to add new operations to
existing object structures without actually modifying those structures.
*/

interface RoleVisitorInterface {
    public function visitUser(User $role);
    public function visitGroup(Group $role);
}

class RolePrintVisitor implements RoleVisitorInterface {
    public function visitGroup(Group $role) {
        echo 'Role: ' . $role->getName() . '<br/>';
    }

    public function visitUser(User $role) {
        echo 'Role: ' . $role->getName() . '<br/>';
    }
}

abstract class Role {

    public function accept(RoleVisitorInterface $visitor) {
        $klass = get_called_class();
        preg_match('#([^\\\\]+)$#', $klass, $extract);
        $visitingMethod = 'visit' . $extract[1];

        if (!method_exists(__NAMESPACE__ . '\RoleVisitorInterface', $visitingMethod)) {
            throw new \InvalidArgumentException("The visitor you provide cannot visit a $klass instance");
        }

        call_user_func(array($visitor, $visitingMethod), $this);
    }
}

class User extends Role {
    protected $name;

    public function __construct($name) {
        $this->name = (string)$name;
    }

    public function getName() {
        return 'User ' . $this->name . '<br/>';
    }
}

class Group extends Role {
    protected $name;

    public function __construct($name) {
        $this->name = (string)$name;
    }

    public function getName() {
        return 'Group ' . $this->name . '<br/>';
    }
}

$group = new Group('my group');
$user = new User('my user');
$visitor = new RolePrintVisitor();

$group->accept($visitor);
$user->accept($visitor);
?>

最新文章

  1. sdut 2163:Identifiers(第二届山东省省赛原题,水题)
  2. 去掉NavigationBar底部的黑线
  3. 深入理解HTML5:语义、标准与样式
  4. UVa 12563 (01背包) Jin Ge Jin Qu hao
  5. ASP.NET MVC 数据分页思想及解决方案代码
  6. SSH调试
  7. CF192div2-330B - Road Construction
  8. 什么是JSONP以及它是怎么产生的
  9. html基础标签-2-textarea文本域
  10. mysql初学,mysql修改,mysql查找,mysql删除,mysql基本命令
  11. java数据库之JDBC
  12. 配置rsync+inotify实时同步
  13. WPF打印京东电子面单(可以异步)
  14. django2.0 + python3.6 在centos7 下部署生产环境的一些注意事项
  15. 为SNP增加种族人群频率
  16. 如何关闭windows server2012 80端口
  17. PHP(控制语句,随机数,循环语法)
  18. python函数:基础函数调用整理
  19. Error: cannot allocate vector of size 88.1 Mb问题
  20. Linux 2.6.16 TCP连接速度异常的问题分析

热门文章

  1. JVM系列之三:类装载器子系统
  2. spring( 二 ) DispatcherServlet
  3. LeetCode题库整理(自学整理)
  4. sql 自动增加排序 并且初始值是000001
  5. Kelp.Net是一个用c#编写的深度学习库
  6. 修咻咻对追光的人、云打印团队的Beta产品测试报告
  7. Beta冲刺(8/7)——2019.5.30
  8. Nginx php上传文件大小的设置
  9. 「福利」Java Swing 编写的可视化算法工程,包含树、图和排序
  10. asp.net core MVC 入门学习