定义:将请求封装成一个对象,从而让你是用不同的请求把客户端参数化,对请求排队或者记录请求日志,可以提供命令的撤销和恢复功能。
UML类图:
C++实现:
#include<iostream>
#include<string>
#include<mutex>
#include<stack>
using namespace std;
class Command
{
public:
virtual void execute() = 0;
virtual ~Command() = default;
};
class AutoBusiness
{
public:
void buy()
{
cout << "Buy" << endl;
}
void Sale()
{
cout << "Sale" << endl;
}
};
class BuyCommand :public Command
{
public:
AutoBusiness* ab;
BuyCommand(AutoBusiness* ab)
{
this->ab = ab;
}
// 通过 Command 继承
virtual void execute() override
{
ab->buy();
}
virtual ~BuyCommand() {}
};
class SaleCommand :public Command
{
public:
AutoBusiness* ab;
SaleCommand(AutoBusiness* ab)
{
this->ab = ab;
}
// 通过 Command 继承
virtual void execute() override
{
ab->Sale();
}
virtual ~SaleCommand() {}
};
class Invoker
{
stack<Command*> commandList;
Command* eCommand;
public:
void tackCommand(Command* command)
{
commandList.push(command);
}
void action()
{
if (!commandList.empty())
{
eCommand = commandList.top();
commandList.pop();
eCommand->execute();
}
else
{
cout << "is not command!" << endl;
}
}
};
int main()
{
Invoker* iv = new Invoker();
AutoBusiness* ab = new AutoBusiness();
SaleCommand* saleCommand = new SaleCommand(ab);
BuyCommand* buyCommand = new BuyCommand(ab);
iv->tackCommand(saleCommand);
iv->tackCommand(buyCommand);
iv->action();
iv->action();
iv->action();
return 0;
}
C#实现:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using static System.Console;
namespace ConsoleApp1
{
interface Command
{
void execute();
}
class BuyCommand : Command
{
AutoBusiness ab;
public BuyCommand(AutoBusiness ab)
{
this.ab = ab;
}
public void execute()
{
ab.Buy();
}
}
class SaleCommand : Command
{
AutoBusiness ab;
public SaleCommand(AutoBusiness ab)
{
this.ab = ab;
}
public void execute()
{
ab.Sale();
}
}
class AutoBusiness
{
public void Sale()
{
WriteLine("Sale");
}
public void Buy()
{
WriteLine("Buy");
}
}
class Invoker
{
private Stack<Command> commandList = new Stack<Command>();
private Command eCommand;
public void tackCommand(Command command)
{
commandList.Push(command);
}
public void action()
{
if (commandList.Count > 0)
{
eCommand = commandList.Pop();
eCommand.execute();
}
else
WriteLine("is not Command!");
}
}
class Program
{
static void Main(string[] args)
{
Invoker iv = new Invoker();
AutoBusiness ab = new AutoBusiness();
SaleCommand saleCommand = new SaleCommand(ab);
BuyCommand buyCommand = new BuyCommand(ab);
iv.tackCommand(saleCommand);
iv.tackCommand(buyCommand);
iv.action();
iv.action();
iv.action();
}
}
}