69,373
社区成员
发帖
与我相关
我的任务
分享
#ifndef CSINGLETON_H
#define CSINGLETON_H
#include <stdlib.h>
typedef struct {
void* (*ctor)(void *_self);
void* (*dtor)(void *_self);
void* (*createInstance)(void *self);
void *instance;
} _CSingleton;
extern const void *CSingleton;
void *GetInstance(void);
#endif
csingleton.c
[cpp] view plain copy
#include "csingleton.h"
#include <stdlib.h>
static void *csingletonCtor(void *_self) {
_CSingleton *self = _self;
self->instance = _self;
return self;
}
static void *csingletonDtor(void *_self) {
_CSingleton *self = _self;
self->instance = NULL;
return self;
}
static void *csingletonCreateInstance(void *_self) {
_CSingleton *self = _self;
self->instance = _self;
return self;
}
static _CSingleton _csingleton = {
csingletonCtor, csingletonDtor, csingletonCreateInstance, NULL
};
const void *CSingleton = &_csingleton;
void *GetInstance(void) {
if (NULL == ((_CSingleton*)CSingleton)->instance) {
return csingletonCtor(CSingleton);
} else {
return ((_CSingleton*)CSingleton)->instance;
}
}
main.c
[cpp] view plain copy
#include "csingleton.h"
#include <stdio.h>
int main(int argc, char *argv[]) {
void *ps1 = GetInstance();
void *ps2 = GetInstance();
if (ps1 == ps2) {
fprintf(stdout, "ps1 = ps2\n");
}
return 0;
}
typedef int *SINGLETON; /* 定义自己的类型 */
SINGLETON *singleton = NULL;
pthread_mutex_t singleton_lock=PTHREAD_MUTEX_INITIALIZER;
SINGLETON *init_singleton(void)
{
pthread_mutex_lock(&singleton_lock);
if (NULL == singleton)
{
singleton = calloc(1, sizeof(SINGLETON));
if (NULL == singleton)
{
pthread_mutex_unlock(&singleton_lock);
return NULL;
}
/* SINGLETON 初始化 */
}
pthread_mutex_unlock(&singleton_lock);
return singleton;
}
c里面搞出个单例,干什么用呢?
没怎么研究过单例模式,可以参考一下别人的: http://cantellow.iteye.com/blog/838473 https://baike.baidu.com/item/%E5%8D%95%E4%BE%8B%E6%A8%A1%E5%BC%8F/5946627?fr=aladdin http://blog.chinaunix.net/uid-22291256-id-3486413.html
c里面搞出个单例,干什么用呢?
看你的问题,让我想起了马大师关于臭虫药的相声
单例模式是设计模式里的概念,是独立于语言的,很多语言都可以实现单例模式,C语言也可以,只是优雅程度不高 单例模式是限制只生成一个实例,单线程--多线程--分布式是另外的概念
c里面搞出个单例,干什么用呢?