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?
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.
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'.
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.
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().
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.
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.