Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing Visitor Pattern while allowing different return types of functions

I am trying to implement the Visitor Pattern for an object structure which has methods with different return types (string, signed int, unsigned int, etc).

Now, in the object hierarchy I have added an Accept method with the following signature (using C++):

void Accept(Visitor *);

I am unable to figure out how I can use the same interface (with void return type ) while at the same time allowing my concrete methods to have different return types.

like image 822
spiritusozeans Avatar asked Apr 15 '12 18:04

spiritusozeans


People also ask

What are the examples of visitor design patterns?

Visitor pattern is used when we have to perform an operation on a group of similar kind of Objects. With the help of visitor pattern, we can move the operational logic from the objects to another class. For example, think of a Shopping cart where we can add different type of items (Elements).

What is the purpose of visitor pattern in design pattern?

The purpose of a Visitor pattern is to define a new operation without introducing the modifications to an existing object structure.

In which scenario would you use the visitor pattern?

The visitor pattern is used when: Similar operations have to be performed on objects of different types grouped in a structure (a collection or a more complex structure). There are many distinct and unrelated operations needed to be performed.


1 Answers

The Accept method in the type hierarchy is just a dispatcher, and has no return type. If what you want is the visitation to produce a value the simplest way would be to add that as part of the state of the visitor:

struct times2 : visitor {
   double value;
   times2() : value() {}
   void operator()( int x ) { value = x * 2; }
   void operator()( double x ) { value = x * 2; }
};

object o;
times2 v;
o.accept( v );
std::cout << "Result is " << v.value << std::endl;

Then again, the specific details of the visitor will vary with your implementation, but the idea is that you can store the result in the visitor rather than return it.

like image 98
David Rodríguez - dribeas Avatar answered Sep 27 '22 20:09

David Rodríguez - dribeas