我正在尝试编写一些代码,据我所知,这是一个状态机的例子。
到目前为止,我所做的是:
StateInstance
这很好用,但是在我的程序运行期间我只希望存在一个状态。
StateInstanceOption
,StateInstanceMapper
和#include <map>
#include <iostream>
class StateInstance
{
std::string m_string;
public:
// somewhat inconveniently, have to create an entirely new function for each possible instance of the state
static StateInstance& get_instance_a()
{
static StateInstance instance_a("hello world");
return instance_a;
}
static StateInstance& get_instance_b()
{
static StateInstance instance_b("bring me coffee");
return instance_b;
}
private:
StateInstance(const std::string& string)
: m_string{string}
{
}
StateInstance(const StateInstance &) = delete;
StateInstance& operator=(const StateInstance&) = delete;
public:
std::string Get() const
{
return m_string;
}
}; // instance_a("hello world"), instance_b("bring me coffee");
enum class StateInstanceOption
{
STATE_INSTANCE_A,
STATE_INSTANCE_B
}gCurrentState{StateInstanceOption::STATE_INSTANCE_A}; // global variable to hold current state "pointer" (really a flag)
class StateInstanceMapper
{
std::map<StateInstanceOption, const StateInstance&> m_map;
public:
static StateInstanceMapper& getInstance()
{
static StateInstanceMapper instance;
return instance;
}
private:
StateInstanceMapper()
{
m_map.insert(std::pair<StateInstanceOption, const StateInstance&>(StateInstanceOption::STATE_INSTANCE_A, StateInstance::get_instance_a()));
m_map.insert(std::pair<StateInstanceOption, const StateInstance&>(StateInstanceOption::STATE_INSTANCE_B, StateInstance::get_instance_b()));
}
StateInstanceMapper(const StateInstanceMapper &) = delete;
StateInstanceMapper& operator=(const StateInstanceMapper &) = delete;
public:
const StateInstance& DoMap(/*const StateInstanceOption opt*/) const
{
return m_map.at(/*opt*/ gCurrentState);
}
}; //mapper_instance;
int main()
{
//std::cout << mapper_instance.DoMap(/*gCurrentState*/).Get() << std::endl;
std::cout << StateInstanceMapper::getInstance().DoMap().Get() << std::endl;
gCurrentState = StateInstanceOption::STATE_INSTANCE_B;
//std::cout << mapper_instance.DoMap(/*gCurrentState*/).Get() << std::endl;
std::cout << StateInstanceMapper::getInstance().DoMap().Get() << std::endl;
return 0;
}
对于函数的例子,(在C中),我会使函数变为静态,并将函数放在一个单独的头文件中,从而防止在其他文件中看到它。
有什么办法可以阻止最终用户创建这些对象的更多实例吗?
http://10.0.2.2:<hostport>
答案 0 :(得分:-1)
您要创建的是singleton,将构造函数设为私有,并提供将提供单例实例的函数。
作为C ++中单例的一个例子:
class Singleton {
std::string message;
// Private constructor
Singleton(const std::string& s) : message(s) {}
public:
static Singleton& instance() {
static Singleton s ("Hello!");
return s;
}
const std::string& get_message() {
return message;
}
}