访客模式不应该重构吗?
Shouldn't the visitor pattern be refactored?
目前我正在从事一个利用 Visitor Pattern 的项目。在使用这种模式时,我发现自己在写评论,例如:
* @param VisitorInterface $visitor The visitor to visit.
访问者模式由以下接口组成:
VisitorInterface {
public function visit($object);
}
VisitableInterface {
public function accept(VisitorInterface $visitor);
}
现在我的问题是:不应该相反吗?
VisitorInterface {
public function accept($object);
}
VisitableInterface {
public function visit(VisitorInterface $visitor);
}
因为现在访问者将接受要访问的东西,因为访问者应该是访问某物的东西。而可访问对象现在将接受访问者。
例如:
class Party implements VisitableInterface {
public function visit(VisitorInterface $visitor) {
$visitor->accept($this);
}
}
class Human implements VisitorInterface {
public function accept($object) {
// do something with object
}
}
所以现在我们有一个接待访客的派对。可以要求这些访客接受聚会的东西来做某事。
我希望已经充分解释了我对此的想法,以展示我的 "concern"。请不要怪我试图打破设计模式:-)
方法是在 object 上使用参数调用的,而不是在参数上调用的。所以,如果你调用 human.visit(party)
,这意味着人类访问了某物,并且在参数中指定了什么 - 派对。
目前我正在从事一个利用 Visitor Pattern 的项目。在使用这种模式时,我发现自己在写评论,例如:
* @param VisitorInterface $visitor The visitor to visit.
访问者模式由以下接口组成:
VisitorInterface {
public function visit($object);
}
VisitableInterface {
public function accept(VisitorInterface $visitor);
}
现在我的问题是:不应该相反吗?
VisitorInterface {
public function accept($object);
}
VisitableInterface {
public function visit(VisitorInterface $visitor);
}
因为现在访问者将接受要访问的东西,因为访问者应该是访问某物的东西。而可访问对象现在将接受访问者。
例如:
class Party implements VisitableInterface {
public function visit(VisitorInterface $visitor) {
$visitor->accept($this);
}
}
class Human implements VisitorInterface {
public function accept($object) {
// do something with object
}
}
所以现在我们有一个接待访客的派对。可以要求这些访客接受聚会的东西来做某事。
我希望已经充分解释了我对此的想法,以展示我的 "concern"。请不要怪我试图打破设计模式:-)
方法是在 object 上使用参数调用的,而不是在参数上调用的。所以,如果你调用 human.visit(party)
,这意味着人类访问了某物,并且在参数中指定了什么 - 派对。