本文介绍了PHP的设计模式 - 访客模式与仆人模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现这两个模式是相似的(和大多数其他行为模式)

I find these two patterns are similar (and the most of other behavioral patterns)

访问者模式

interface Visitor
{
    public function visit(Visitable $Visitable);
}
interface Visitable
{
    public function accept(Visitor $Vsitor);
}
class ConcreteVisitable implements Visitable
{
    public $items = array();

    public function addItem($item)
    {
        $this->items[] = $item;
    }

    public function accept(Visitor $Vsitor)
    {
        $Vsitor->visit($this);
    }
}
class ConcreteVisitor implements Visitor
{
    protected $info;

    public function visit(Visitable $Visitable)
    {
        echo "Object: ", get_class($Visitable), " <br/>";
        $items = get_object_vars($Visitable)['items'];

        foreach ($items as $index => $value) {
            echo $index . ": ", $value, " <br/>";
        }
    }
}
// Usage example
$ConcreteVisitable = new ConcreteVisitable();
$ConcreteVisitor = new ConcreteVisitor();
$ConcreteVisitable->addItem('item 1');
$ConcreteVisitable->addItem('item 2');
$ConcreteVisitable->addItem('item 3');
$ConcreteVisitable->accept($ConcreteVisitor);

仆人模式,

// Servant.
interface Servant
{
    //
}

// Servable. AKA Boss/ Master/ Authority
interface Servable
{
    //
}

// Concrete Servable.
class ConcreteServable implements Servable
{
    private $position;

    public function setPosition($position)
    {
        $this->position = $position . '<br/>';
    }

    public function getPosition()
    {
        return $this->position;
    }
}

// Concrete Servant.
class ConcreteServant implements Servant
{
    // Method, which will move Servable implementing class to position where.
    public function moveTo(Servable $Servable, $arg)
    {
        // Do some other stuff to ensure it moves smoothly and nicely, this is
        // the place to offer the functionality.
        $Servable->setPosition($arg);
    }
}

$ConcreteServable = new ConcreteServable();
$ConcreteServant = new ConcreteServant();

$ConcreteServant->moveTo($ConcreteServable, 10);
echo $ConcreteServable->getPosition();

$ConcreteServant->moveTo($ConcreteServable, 20);
echo $ConcreteServable->getPosition();

你可以告诉他们之间的区别吗? (除非仆人模式示例不正确?)

Can you tell the differences between them? (unless the servant pattern example is incorrect??)

推荐答案

事实上,仆人比访问者模式更简单。类图也是类似的。
在访问者模式中,Visitor对象依赖于访问元素,但服务对象不是。

in fact, servant is simpler than visitor pattern. The class diagram is similar, too.In visitor pattern, Visitor object rely on visited elements, but serviced object not.

这篇关于PHP的设计模式 - 访客模式与仆人模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 18:45