Question

I'm quite new to this pattern...

Was it helpful?

Solution

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.

OTHER TIPS

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).

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).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top