php访问者模式(visitor design)
2024-08-26 22:28:03
终于搞定,累成一滩,今晚不想说话。
<?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); ?>
最新文章
- sdut 2163:Identifiers(第二届山东省省赛原题,水题)
- 去掉NavigationBar底部的黑线
- 深入理解HTML5:语义、标准与样式
- UVa 12563 (01背包) Jin Ge Jin Qu hao
- ASP.NET MVC 数据分页思想及解决方案代码
- SSH调试
- CF192div2-330B - Road Construction
- 什么是JSONP以及它是怎么产生的
- html基础标签-2-textarea文本域
- mysql初学,mysql修改,mysql查找,mysql删除,mysql基本命令
- java数据库之JDBC
- 配置rsync+inotify实时同步
- WPF打印京东电子面单(可以异步)
- django2.0 + python3.6 在centos7 下部署生产环境的一些注意事项
- 为SNP增加种族人群频率
- 如何关闭windows server2012 80端口
- PHP(控制语句,随机数,循环语法)
- python函数:基础函数调用整理
- Error: cannot allocate vector of size 88.1 Mb问题
- Linux 2.6.16 TCP连接速度异常的问题分析