开发者

Singleton Pattern in C [duplicate]

开发者 https://www.devze.com 2023-02-14 15:32 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: How to create a Singleton in C ?
This question already has answers here: Closed 11 years ago.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消