#include <iostream>
#include <memory>
template <typename T> class Interface
{
public:
using SharedPtr = std::shared_ptr<T>;
using WeakPtr = std::weak_ptr<T>;
static WeakPtr reg(SharedPtr impl)
{
instance().m_impl = impl;
return impl;
}
static void unreg() { instance().m_impl.reset(); }
static SharedPtr interface() { return instance().m_impl; }
private:
SharedPtr m_impl;
static Interface &instance()
{
static Interface inst;
return inst;
}
};
class AbscractConfig
{
public:
virtual void set(int value) = 0;
virtual int get() = 0;
};
class Impl : public AbscractConfig
{
public:
Impl() { std::cout << "Impl" << std::endl; }
~Impl() { std::cout << "~Impl" << std::endl; }
void set(int value) override { m_value = value; }
int get() override { return m_value; }
private:
int m_value = 222;
};
static auto configInstance =
Interface<AbscractConfig>::reg(std::make_shared<Impl>());
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;
config.reset();
Interface<AbscractConfig>::unreg();
std::cout << "--------------------" << std::endl;
return 0;
}