C++ 九阴真经之单例模式
单例类在日常开发中是非常常见的,用于管理一些配置数据及资源,提供全局访问。
通过单例模式, 可以做到:
- 确保一个类只有一个实例被建立
- 提供了一个对对象的全局访问指针
- 在不影响单例类的客户端的情况下允许将来有多个实例
代码实现:
//单例
template<typename T>
class Singleton : public noncopyable
{
public:
    static T & get_instance() {
        static T ins;
        do_nothing(instance);
        return ins;
    }
private:
    static T & instance;
    static void do_nothing(T const &) {}
};
template<typename T>
T & Singleton< T >::instance = Singleton< T >::get_instance();
 
优点:
- 编译期实例化,避免在多线程环境下产生多个实例。
- 与业务类分离,用户根据需要可自行定义多份单例,比较灵活。
测试代码:
class Test
{
public:
    Test()
    {
        std::cout << "创建对象" << std::endl;
        a = 100;
        m_val = {{"1234", "234"}};
    }
    int a;
    std::map<std::string, std::string> m_val;
};
using TestAgent = Singleton<Test>;
int main()
{
    std::cout << "开始" << std::endl;
    TestAgent::get_instance().a = 10;
    std::cout << "value:" << TestAgent::get_instance().a << std::endl;
    return 0;
}
 
运行结果:
创建对象
开始
value:10
                    来源:oschina
链接:https://my.oschina.net/u/3312209/blog/4291679