Visitor Pattern + Open/Closed Principle

馋奶兔 提交于 2019-12-31 10:36:16

问题


Is it possible to implement the Visitor Pattern respecting the Open/Closed Principle, but still be able to add new visitable classes?

The Open/Closed Principle states that "software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification".

struct ConcreteVisitable1;
struct ConcreteVisitable2;

struct AbstractVisitor
{
   virtual void visit(ConcreteVisitable1& concrete1) = 0;
   virtual void visit(ConcreteVisitable2& concrete2) = 0;
};

struct AbstractVisitable
{
   virtual void accept(AbstractVisitor& visitor) = 0;
};

struct ConcreteVisitable1 : AbstractVisitable
{
   virtual void accept(AbstractVisitor& visitor)
   {
      visitor.visit(*this);
   }
};

struct ConcreteVisitable2 : AbstractVisitable
{
   virtual void accept(AbstractVisitor& visitor)
   {
      visitor.visit(*this);
   }
};

You can implement any number of classes which derives from AbstractVisitor: It is open for extension. You cannot add a new visitable class as the classes derived from AbstractVisitor will not compile: It closed for modification.

The AbstractVisitor class tree respects the Open/Closed Principle. The AbstractVisitable class tree does not respect the Open/Closed Principle, as it cannot be extended.

Is there any other solution than to extend the AbstractVisitor and AbstractVisitable as below?

struct ConcreteVisitable3;

struct AbstractVisitor2 : AbstractVisitor
{
   virtual void visit(ConcreteVisitable3& concrete3) = 0;
};

struct AbstractVisitable2 : AbstractVisitable
{
   virtual void accept(AbstractVisitor2& visitor) = 0;
};

struct ConcreteVisitable3 : AbstractVisitable2
{
   virtual void accept(AbstractVisitor2& visitor)
   {
      visitor.visit(*this);
   }
};

回答1:


In C++, Acyclic Visitor (pdf) gets you what you want.




回答2:


You might want to check out research on "the expression problem", see e.g.

http://lambda-the-ultimate.org/node/2232

I think the problem is mostly academic, but it's something that has been studied a lot, so there's a bit of stuff you can read about different ways to implement it in existing languages or with various language extensions.



来源:https://stackoverflow.com/questions/171755/visitor-pattern-open-closed-principle

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