Design patterns for PHP - visitor pattern vs servant pattern

天涯浪子 提交于 2019-12-10 11:23:05

问题


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

visitor pattern,

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 pattern,

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


回答1:


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.



来源:https://stackoverflow.com/questions/27939046/design-patterns-for-php-visitor-pattern-vs-servant-pattern

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!