您可以创建一个 Operation 基类,然后将其派生两次以创建 Insert 和 Erase 类。然后,您可以存储指向 Operation 类的指针。
class Settings
{
public:
bool Insert(std::string const& key, std::string const& value)
{
m_operations.push_back(new Insert(key, value));
return true; //?
}
bool Erase(std::string const& key)
{
m_operations.push_back(new Erase(key));
return true; //?
}
bool Commit()
{
// You know what to do by now right ?
}
private:
class Operation
{
public:
virtual void Execute() = 0
}
class Insert : public Operation
{
public:
Insert(std::string const& key, std::string const& value) :
m_key(key), m_value(value) {}
void Execute() {...}
private:
std::string m_key;
std::string m_value;
}
class Erase : public Operation
{
public:
Erase(std::string const& key) : m_key(key) {}
void Execute() {...}
private:
std::string m_key;
}
std::queue<Operation*> m_operations;
std::map<std::string, std::string> m_settings;
}
然后你要么让你的操作类成为设置类的朋友,要么你将一个引用传递给应该应用操作的地图。