#include <iostream>
#include <memory>
template <typename T> class Interface
{
public:
static Interface &instance()
{
static Interface inst;
return inst;
}
static void reg(T *impl) { instance().m_impl = impl; }
static void unreg() { instance().m_impl = nullptr; }
static T *interface() { return instance().m_impl; }
private:
T *m_impl;
};
class AbscractConfig
{
public:
virtual void set(int value) = 0;
virtual int get() = 0;
};
class Impl : public AbscractConfig
{
public:
Impl() { Interface<AbscractConfig>::reg(this); }
~Impl() { Interface<AbscractConfig>::unreg(); }
void set(int value) override { m_value = value; }
int get() override { return m_value; }
private:
int m_value;
};
static Impl implInst;
int main(int argc, char const *argv[])
{
auto config = Interface<AbscractConfig>::interface();
std::cout << "hello: " << config << std::endl;
config->set(456);
std::cout << "value: " << config->get() << std::endl;
return 0;
}
标签:int,value,instance,static,接口,注册,Interface,impl,C++
From: https://www.cnblogs.com/kevinjen/p/17749739.html