PHP的设计模式 - 访问者模式与服务模式

时间:2015-01-14 08:59:47

标签: php design-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.
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();

你能说出它们之间的区别吗? (除非服务方模式示例不正确?)

1 个答案:

答案 0 :(得分:2)

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