Visitor Pattern + Open/Closed Principle
Asked Answered
B

2

17

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);
   }
};
Beniamino answered 5/10, 2008 at 9:37 Comment(0)
H
8

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

Hilde answered 5/10, 2008 at 10:55 Comment(1)
Also see: butunclebob.com/ArticleS.UncleBob.VisitorVersusInstanceOf which compares three alternatives.Koziel
W
4

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.

Wenzel answered 5/10, 2008 at 9:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.