#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
typedef struct _singleton_t
{
int data;
}singleton_t;
/* 全局静态指针(指向唯一实例) */
static singleton_t* s_singleton = NULL;
static singleton_t* singleton_create(void)
{
s_singleton = (singleton_t*)malloc(sizeof(singleton_t));
s_singleton->data = 0; // 数据初始化
return s_singleton;
}
singleton_t* singleton() {
if (s_singleton == NULL) {
singleton_create(); /* 调用构造函数实例化 */
}
assert(s_singleton != NULL);
return s_singleton;
}
void singleton_destroy() {
if (s_singleton != NULL) {
free(s_singleton);
}
}
int main(int argc, char *argv[])
{
singleton_t* singleton1 = singleton();
singleton1->data = 10;
singleton_t* singleton2 = singleton();
singleton2->data = 20;
if (singleton1 == singleton2) {
printf("singleton1 == singleton2\n");
}
printf("singleton1->data = %d\n", singleton1->data);
printf("singleton2->data = %d\n", singleton2->data);
singleton_destroy();
//system("pause");
return 0;
}
参考链接