c语言与设计模式(1)——单例模式

万事开头难,所以我先捡一个简单的来写,希望后面越写越简单(aws: 长得丑,想得美)。

单例模式可以说是最简单的设计模式了,

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

 

 

代码如下,

/******************************************************************/

/*singleton.h*/

#ifndef __SINGLETON_H__

#define __SINGLETON_H__

 

struct singleton {

struct singleton *instance;

int priv_x, priv_y;

};

 

extern struct singleton *get_instance();

 

#endif

 

/*lazy_singleton.c: 懒汉模式的实现*/

#include <stdio.h>

#include <stdlib.h>

#include <assert.h>

#include <pthread.h>

 

#include "singleton.h"

 

 

static pthread_mutex_t singleton_mutex;

 

static void singleton_initialize(struct singleton *psg, int x, int y)

{

psg->priv_x = x;

psg->priv_y = y;

}

 

struct singleton *get_instance()

{

static struct singleton *instance = NULL;

 

/*DCL*/

if (NULL == instance) {

pthread_mutex_lock(&singleton_mutex);

if (NULL == instance) {

printf("malloc instance\n");

instance = malloc(sizeof(struct singleton));

assert(NULL != instance);

singleton_initialize(instance, 1, 2);

}

pthread_mutex_unlock(&singleton_mutex);

}

return instance;

}

 

/*hungry_singleton.c: 饿汉模式的实现*/

#include <stdio.h>

#include "singleton.h"

 

struct singleton *get_instance()

{

static struct singleton sgt = {

.priv_x = 3,

.priv_y = 4

};

 

return &sgt;

}

 

相关代码已同步到github上:https://github.com/chenchuangchn/design_pattern_with_c.git

/******************************************************************/

最后,让给我们恭喜AG超玩会夺得KPL总冠军。出道即巅峰,随着版本更迭而陨落,之后历尽千帆,归来称王。夺冠后老帅啜泣不止,从中路万花筒到离开AG到不成功的转型的其他队伍的边路,再沦为替补,被嘲讽菜,再到转会除了AG没人要,顶着舆论的压力,拿到了冠军,一切冷暖心酸谁又能知;而他又是何其的幸运,把所有的压抑通过夺冠释放了出来。在这个成王败寇的游戏规则里,只有成功才能放肆的哭。就像王者荣耀说的那样——“到达胜利之前,无法回头!”

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值