Singleton Pattern in C [duplicate]

风格不统一 提交于 2019-12-14 03:43:09

问题


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++]?


回答1:


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;
}



回答2:


You can just declare:

char sharedData[256];

That's a global variable, no struct and singleton-antipattern needed.



来源:https://stackoverflow.com/questions/5171661/singleton-pattern-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!