C로 짜본 짝퉁 싱글턴
2009/09/18 11:51
말이 싱글턴이지.. 만들어놓고 보니 그냥 캡슐화임.
헤더파일은 이런식으로.
//Header File. 'cfg.h'
typedef struct { int (*getA)(void); void (*setA)(int _a); char (*getB)(void); void (*setB)(char _b); double (*getC)(void); void (*setC)(double _c); }config;
config* getConfig(void);
소스코드는 이런식.
//Source File. 'cfg.c' #include "cfg.c"
config* self=NULL;
static int a; static char b; static double c;
static int getA(void){return a;} static void setA(int _a){a=_a;} static char getB(void){return b;} static void setB(char _b){b=_b;} static double getC(void){return c;} static void setC(double _c){c=_c;}
config* getConfig() { if(self==NULL) { self = (config*)malloc(sizeof(config)); self->getA = getA; self->setA = setA; self->getB = getB; self->setB = setB; self->getC = getC; self->setC = setC; } return self; }
외부에서 include해서 쓰면 됨.
#include <stdio.h> #include "cfg.h"
int main(void) { config* cfg=getConfig(); cfg->setA(10); cfg->setB('a'); cfg->setC(123.456); printf("%d/%c/%f\n\n", cfg->getA(),cfg->getB(),cfg->getC());
getConfig()->setA(20); getConfig()->setB('b'); getConfig()->setC(456.789); printf("%d/%c/%f\n", getConfig()->getA(),getConfig()->getB(),getConfig()->getC());
return 0;
}
이거 심각한 문제점이 있는데..
config 을 하나만 생성하게 할 방법이 없다.
(물론 config을 만든다고 해서 접근가능한 건 아니다. 함수포인터가 매칭이 안됐으니 런타임에러가 나겠지.)
그냥 아무생각없이 getConfig() 만 땡겨다 쓰면 되겠지 뭐.
뭐 편한대로
config* cfg = getConfig(); cfg->뭐시기 형태로 쓰던지
그것도 귀찮으면 getConfig->뭐시기 형태로 쓰던지.

