万事开头难,所以我先捡一个简单的来写,希望后面越写越简单(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没人要,顶着舆论的压力,拿到了冠军,一切冷暖心酸谁又能知;而他又是何其的幸运,把所有的压抑通过夺冠释放了出来。在这个成王败寇的游戏规则里,只有成功才能放肆的哭。就像王者荣耀说的那样——“到达胜利之前,无法回头!”