Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Command pattern
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
== Example == <!-- Wikipedia is not a list of examples. Do not add examples from your favorite programming language here; this page exists to explain the design pattern, not to show how it interacts with subtleties of every language under the sun. Feel free to add examples here: http://en.wikibooks.org/wiki/Computer_Science_Design_Patterns/Command --> This C++14 implementation is based on the pre C++98 implementation in the book. <syntaxhighlight lang="c++"> #include <iostream> #include <memory> class Command { public: // declares an interface for executing an operation. virtual void execute() = 0; virtual ~Command() = default; protected: Command() = default; }; template <typename Receiver> class SimpleCommand : public Command { // ConcreteCommand public: typedef void (Receiver::* Action)(); // defines a binding between a Receiver object and an action. SimpleCommand(std::shared_ptr<Receiver> receiver_, Action action_) : receiver(receiver_.get()), action(action_) { } SimpleCommand(const SimpleCommand&) = delete; // rule of three const SimpleCommand& operator=(const SimpleCommand&) = delete; // implements execute by invoking the corresponding operation(s) on Receiver. virtual void execute() { (receiver->*action)(); } private: Receiver* receiver; Action action; }; class MyClass { // Receiver public: // knows how to perform the operations associated with carrying out a request. Any class may serve as a Receiver. void action() { std::cout << "MyClass::action\n"; } }; int main() { // The smart pointers prevent memory leaks. std::shared_ptr<MyClass> receiver = std::make_shared<MyClass>(); // ... std::unique_ptr<Command> command = std::make_unique<SimpleCommand<MyClass> >(receiver, &MyClass::action); // ... command->execute(); } </syntaxhighlight> The program output is <syntaxhighlight lang="c++"> MyClass::action </syntaxhighlight>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)