zoukankan      html  css  js  c++  java
  • 使用方便的单例类

    此处输入图片的描述

    前言

    我们在软件开发中会经常用到设计模式,其中运用的最为广泛的设计模式就是单例,下面是实现单例类的代码。

    单例类

    #pragma once
    
    template <typename T>
    class singleton
    {
    public:
    	singleton() = delete;
    	virtual ~singleton() = delete;
    	singleton(const singleton&) = delete;
    	singleton& operator=(const singleton&) = delete;
    
    	template<typename... Args>
    	static T& get_instance(Args&&... args)
    	{
    	    // C++11保证单例的线程安全
    		static T t{ std::forward<Args>(args)... };
    		return t;
    	}
    };
    
    #define DEFINE_SINGLETON(class_name) 
    public: 
    friend class singleton<class_name>; 
    using singleton = singleton<class_name>; 
    private: 
    virtual ~class_name() {} 
    class_name(const class_name&) = delete; 
    class_name& operator=(const class_name&) = delete; 
    public:
    
    

    使用

    #include <iostream>
    #include <string>
    #include "singleton.h"
    
    class test
    {
        // 只需要加入一句代码,就可以将test类变为单例类
    	DEFINE_SINGLETON(test);
    public:
    	test() = default;
    	void print()
    	{
    		std::cout << "Hello world" << std::endl;
    	}
    };
    
    class test2
    {
        // 只需要加入一句代码,就可以将test2类变为单例类
    	DEFINE_SINGLETON(test2);
    public:
    	test2(const std::string& str) : str_(str) {}
    
    	void print()
    	{
    		std::cout << str_ << std::endl;
    	}
    
    private:
    	std::string str_;
    };
    
    int main()
    {
        // 没有参数的单例
    	test::singleton::get_instance().print();
    	// 带有参数的单例
    	test2::singleton::get_instance("nihao").print();
    	return 0;
    }
    
  • 相关阅读:
    微博深度学习平台架构和实践
    2020暑期学习
    2020春季学期个人课程总结
    人月神话阅读笔记03
    人月深化阅读笔记02
    第十六周学习总结
    人月神话阅读笔记01
    三分算法
    [SDOI2010]魔法猪学院
    【洛谷】NOIP2018原创模拟赛DAY1解题报告
  • 原文地址:https://www.cnblogs.com/highway-9/p/6105126.html
Copyright © 2011-2022 走看看