views:

1547

answers:

6

I am very familiar with the Command pattern, but I don't yet understand the difference in theory between a Functor and a command. In particular, I am thinking of Java implementations. Both are basically programming "verbs" represented as objects. However, in the case of functors, as I have seen from some examples anonymous inner class implementations seem common. Can anyone out there clear this up for me nicely?

+4  A: 

From the description of the Apache Commons Functor page:


A functor is a function that can be manipulated as an object, or an object representing a single, generic function.

Functors support and encourage a number of powerful programming techniques including:

  • programming in a functional style
  • higher order functions
  • internal iterators
  • reuse and specialization through composition rather than inheritance and overloading
  • generic "callback" or "extension point" APIs
  • generic "filters" or predicate APIs
  • many "behavioral" design patterns, such as Visitor, Strategy, Chain of Responsibility, etc.
mkoeller
+9  A: 

A functor is an implementation, a way of making an object behave like a function.

The 'Command Pattern' is a design pattern.
The functor is one way to implement the 'Command Pattern'.

Martin York
@Martin York: You might want to add "Marketing" -- Command has better marketing than 'Functor'.
S.Lott
+2  A: 

I think of a functor as being a component of the command pattern, which also involves other infrastructure such as the invoker and command recipients.

marijne
+3  A: 

A functor is a 'syntax level' concept - it packages up code in an object that can be treated syntactically like a function pointer - i.e. it can be 'called' by putting parameter list in brackets after it. In C++ you could make a class a functor by overriding operator().

A Command in the command pattern is an object that packages up some runnable functionality, but there's no requirement for it to be a functor. For example, it could be a class that implements an interface ICommand, allowing its command to be run by calling Do().

mackenir
+1  A: 

The Command pattern is used in Java because we don't have closures in Java. Functors is an attempt to implement closures.

A language with closures doesn't need the Command pattern.

Steve McLeod
It would probably be more fair to say that (some forms of) the command pattern can be implemented much easier using closures. (And if the command supports undo for example, you need more than just a closure to implement it.)
JacquesB
+1  A: 

Here comes the answer from the GOF:

Coplien describes how to implement functors, objects that are functions, in C++ [Cop92]. He achieves a degree of transparency in their use by overloading the function call operator (operator()). The Command pattern is different; its focus is on maintaining a binding between a receiver and a function (i.e., action), not just maintaining a function.

Comptrol