c++ Design Patterns 23 Command Patterns

Keywords: calculator Google

Command mode

Definition:

Encapsulate different requests into abstract commands and call real class implementations through command internals

Advantage:

(1) Decoupling the requester and the recipient. The requester only needs to issue relevant commands to call the recipient method internally.

(2) Easy to extend new commands

Disadvantages:

(1) It will lead to too many command classes and add middle-level code.

Scope of use:

Callers need systems that categorize requests and implementations, and many command classes that have peer relationships

Such as: calculator addition and subtraction multiplication and division operation commands, the upper and lower role of the game role command and so on.

Structure:

Examples of implementing up and down commands: the client sends specific commands, calls move(), and calls the member variable do_action() of the real action inside the function.

Realization:

namespace behavioral_pattern
{
	class up_action
	{
	public:
		void do_action()
		{
			std::cout << "up move" << std::endl;
		}

	};
	class down_action
	{
	public:
		void do_action()
		{
			std::cout << "down move" << std::endl;
		}
	};
	class command_pattern
	{
	public:
		virtual void move() = 0;
	};

	class up_command_pattern :public command_pattern
	{
	public:
		virtual void move()
		{
			std::cout << "up_command_pattern" << std::endl;
			upact->do_action();
		}
	private:
		std::unique_ptr<up_action> upact{ new up_action() };
	};

	

	class down_command_pattern :public command_pattern
	{
	public:
		virtual void move()
		{
			std::cout << "down_command_pattern" << std::endl;
			downact->do_action();
		}
	private:
		std::unique_ptr<down_action> downact{ new down_action() };
	};
}

Test:

The unit testing framework based on Google Test; the framework can refer to the following web sites:

https://www.cnblogs.com/jycboy/p/gtest_catalog.html

using namespace behavioral_pattern;

TEST(test_command_pattern_move, success_runupclass)
{
	std::unique_ptr<command_pattern> command{ new up_command_pattern() };
	command->move();
}

TEST(test_command_pattern_move, success_rundownclass)
{
	std::unique_ptr<command_pattern> command{ new down_command_pattern() };
	command->move();
}

summary

(1) Command mode is similar to policy mode, which implements methods directly in derived classes, and command mode calls specific implementation class methods.

(2) The caller must know the preconditions for command invocation

(3) Consider macro commands and command queues (additional encapsulated command queue classes use for_each() to execute internal commands, and clients pass in command queue class instances)

Posted by BuzzLY on Mon, 07 Oct 2019 18:11:57 -0700