php访问者模式(visitor design)

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

<?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);
?>

转载于:https://www.cnblogs.com/aguncn/p/11186064.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值