设计模式5-单例模式

引用:C++实现线程安全的单例模式 - myd620 - 博客园

单例模式-地鼠文档

5. 单例模式 — Graphic Design Patterns

单例模式(Singleton Pattern):单例模式确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例,这个类称为单例类,它提供全局访问的方法。

../_images/Singleton.jpg

一、go语言版

package main
import "sync"
import "fmt"
type Singleton struct{}
var singleton *Singleton
var once sync.Once
func GetInstance() *Singleton {
    once.Do(func(){
        singleton = &Singleton{}
    })
    return  singleton 
}
func main() {
    ins1 := GetInstance()
    ins2 := GetInstance()
    if ins1 == ins2 {
        fmt.Printf("instance is equel\n")
    }
}

二、c++语言版

#include <iostream>
#include <pthread.h>
using namespace std;
template <class T>
class singleton
{
private:
    singleton();
    singleton(const singleton&){};
    singleton &operator=(const singleton&){};
    static T* m_instance;
    static pthread_once_t m_once;
public:
    static void init();
    static T* GetInstance();
};
class Test {
public:
    Test() {
        cout << "test construct" << endl;
    }
    void set(int a) {
        cout << "test show" << endl;
        a = a_;
    }
    int get() const {
        return a_;
    }
private:
    int a_;
};
template <class T>
void singleton<T>::init()
{
    cout << "init " << endl;  
    m_instance = new T();
}
template <class T>
T *singleton<T>::GetInstance()
{
    pthread_once(&m_once, init);
    return m_instance;
}
template <class T>
pthread_once_t singleton<T>::m_once = PTHREAD_ONCE_INIT;
template <class T>
T *singleton<T>::m_instance = NULL;
int main()
{
    Test *t1 = singleton<Test>::GetInstance();
    Test *t2 = singleton<Test>::GetInstance();
    
    cout << "addread t1 " << static_cast<void *>(t1) << endl;
    cout << "addread t2 " << static_cast<void *>(t2) << endl;
   
    return 0;
}

三、c语言版

#include <stdio.h>
#include <pthread.h>
#include <malloc.h>
#include <stdlib.h>
typedef struct _DATA
{
    int a;
    void *data;
}DATA;
DATA *data;
pthread_once_t m_once;
void init()
{
    data = (DATA *)malloc(sizeof(DATA));
   if(NULL == data) {
       printf("init failed\n");
       exit(-1);
   } else {
       printf("init success\n");
   }
}
DATA *GetInstance()
{
    pthread_once(&m_once, init);
    return data;
}
int main()
{
    DATA *data,*data2;
    data = GetInstance();
    data->a = 10;
    data2 = GetInstance();
    printf("data1=%d data2=%d\n",data->a, data2->a);
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值