访客模式说明 [英] Visitor Pattern Explanation

查看:93
本文介绍了访客模式说明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我已经阅读了有关访客模式的所有文档,但仍然感到困惑。我从另一个SO问题中选取了这个示例,有人可以帮我理解吗?例如,何时使用访客设计模式?我想我可能已经了解了其中的一部分,但我只是看不到大图。我怎么知道什么时候可以使用它?

So I've read up all the documentation about the Visitor pattern, and I'm still mightily confused. I've taken this example from another SO question, could someone help me understand? For instance when do we use a visitor design pattern? I think I may have understood some of it, but I'm just not able to see the bigger picture. How do I know when I can use it?

class equipmentVisited
{
  virtual void accept(equipmentVisitor* visitor) = 0;
}

class floppyDisk : public equipmentVisited
{
  virtual void accept(equipmentVisitor* visitor);
}

class processor : public equipmentVisited
{
  virtual void accept(equipmentVisitor* visitor);
}

class computer : public equipmentVisited
{
  virtual void accept(equipmentVisitor* visitor);
}

class equipmentVisitor
{
  virtual void visitFloppyDisk(floppyDisk* );
  virtual void visitProcessor(processor* );
  virtual void visitComputer(computer* );
}

// Some additional classes inheriting from equipmentVisitor would be here

equipmentVisited* visited;
equipmentVisitor* visitor;

// Here you initialise visited and visitor in any convenient way

visited->accept(visitor);


推荐答案

访问者模式用于实现 双重发送 。用简单的话来说,这意味着要执行的代码取决于两个对象的运行时类型。

Visitor pattern is used to implement double dispatch. In plain words it means that the code that gets executed depends on runtime types of two objects.

当您调用常规的虚函数时,它会是单个调度:执行的代码取决于单个对象的运行时类型,即您要调用的虚拟方法。

When you call a regular virtual function, it is a single dispatch: the piece of code that gets executed depends on the runtime type of a single object, namely, the one the virtual method of which you are calling.

使用visitor模式,最终要调用的方法取决于两个对象的类型-实现 equipmentVisitor 的对象的类型以及要在其上使用的对象的类型您调用 accept (即 equipmentVisited 子类)。

With the visitor pattern, the method that is being called ultimately depends on the type of two objects - the type of the object implementing the equipmentVisitor, and the type of the object on which you call accept (i.e. the equipmentVisited subclass).

还有其他方法可以在C ++中实现双重调度。 Scott Meyer的更有效的C ++ 对待

There are other ways to implement double dispatch in C++. Item 31 of Scott Meyer's "More Effective C++" treats this subject in depth.

这篇关于访客模式说明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆