Bob Heffernan
Bob Heffernan

Reputation: 3

"Operating" on objects

I have an object that contains, as part of its data, a linked list. Let's call this object LL, for reference sake.

I want to apply what I will call "operators" to instances of LL. So, an operator will, for instance, swap two elements of LL's linked list.

Ordinarily one might put such operators as methods of LL (so, you'd call LL.swap() or whatever) but I want to be able to define new types of operators.

The obvious thing to do, it seems to me, is to define an "Operator" class of objects that accept a pointer to an LL object when constructed. You could then call Operator.go() which would perform the swap.

However, this just doesn't seem right to me (for vague reasons I'm finding hard to articulate).

Other salient facts include:

  1. I will want to perform many of these operations in sequence (so perhaps the overhead should be as low as possible).
  2. There will usually only be a small number of LL objects instantiated.

Is defining an "Operator" class the way to go? Am I crazy for thinking it should be otherwise? The problem is: I'm having trouble imagining what "otherwise" might be. I haven't done any programming in a while and I'm slow in re-adjusting my brain to it.

Upvotes: 0

Views: 74

Answers (1)

Björn Pollex
Björn Pollex

Reputation: 76886

What you have thought of there is called the visitor-pattern, and it is a good and flexible way to add behavior to objects.

Upvotes: 1

Related Questions