Take the 2-minute tour ×

I'm quite new to this pattern...

share|improve this question
add comment

3 Answers

up vote 4 down vote accepted

If you've got lambdas, you don't really need half of "design" "patterns" altogether.

Factory? That's just a function returning new objects. Visitor? Duh! Command? Anonymous function. Interpreter? Function which takes string or whatever. Strategy? It's a function!

That's just lambdas, functions and closures.

The problem is, about 1/3 to 1/2 of them were basically cover-ups for deficiencies in C++ that don't exist in other languages. Although I'm not a huge Perl fan anymore, I have to admit the Perl community caught on to this first (or at least funniest). They pointed out that many of these so-called patterns were actually an implementation of Functional Programming in C++.

So yes, you can use anonymous (or otherwise named) functions where you would use the Command pattern.

share|improve this answer
what's the difference between a lambda and an anonymous function? –  Iain Jun 15 '09 at 10:47
They are synonyms, I guess. –  alamar Jun 15 '09 at 10:48
Nope, there's slight differences - blogs.msdn.com/ericlippert/archive/2007/01/10/… –  Dan F Jun 15 '09 at 10:54
There isn't a difference between lambdas and anonymous functions. There's a difference "between lambdas and anonymous functions in C#". Yet nobody cares: in javascript, for example, there isn't. –  alamar Jun 15 '09 at 10:56
yep, fair point, if I could edit the comment I would. Awesome yegge post btw! –  Dan F Jun 15 '09 at 11:04
show 2 more comments

If your command supports only one operation, you can safely use an anonymous function.

However, it's not uncommon to have more than one operation for each command. E.g. DoCommand/UndoCommand for undo/redo-handling. Or CanExecuteCommand/ExecuteCommand to enabled/disable UI features for the command. Or something like GetLocalizedCommandName. I would use an interface in these cases (instead of e.g. a tuple of anonymous functions).

share|improve this answer
add comment

I would say no, on the basis that a function cannot really encapsulate the details of a command, and if it as anonymous how can both the caller and callee understand what it represents?

(If one wanted to be pedantic, the GoF description of the Copmmand pattern specifically describes the use of an object to do the encpsulation, preclusing a function based implenetation, though that would be nit-picking).

share|improve this answer
can you explain that in more detail? Which details can't be encapsulated? –  Iain Jun 15 '09 at 10:50
add comment

Your Answer


