我发现这两种模式是相似的(以及大多数其他行为模式)
访客模式,
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();
你能说出它们之间的区别吗? (除非服务方模式示例不正确?)
答案 0 :(得分:2)