Singleton Pattern in C [duplicate]
Possible Duplicate:
How to create a Singleton in C ?
Hello, if I have a structure
definition as follows:
struct singleton
{
char sharedData[256];
};
Can I impose the singleton pattern on instance variables of 开发者_运维百科the above structure
in C [not in C++]?
If you just forward declare your struct
in the header file, it will be impossible for clients to create an instance of it. Then you can provide a getter function for your single instance.
Something like this:
.h
:
#ifndef FOO_H
#define FOO_H
struct singleton;
struct singleton* get_instance();
#endif
.c
:
struct singleton
{
char sharedData[256];
};
struct singleton* get_instance()
{
static struct singleton* instance = NULL;
if (instance == NULL)
{
//do initialization here
}
return instance;
}
You can just declare:
char sharedData[256];
That's a global variable, no struct and singleton-antipattern needed.
精彩评论