C中的单例模式

Swa*_*rma 1 c singleton

可能重复:
如何在C中创建单例?

您好,如果我有structure如下定义:

struct singleton
{
    char sharedData[256];
};
Run Code Online (Sandbox Code Playgroud)

我可以structure在C [not in C++] 中将单例模式强加于上述实例变量吗?

Job*_*Job 9

如果您只是struct在头文件中转发声明,则客户端将无法创建它的实例.然后,您可以为单个实例提供getter函数.

像这样的东西:

.h:

#ifndef FOO_H
#define FOO_H

struct singleton;

struct singleton* get_instance();

#endif
Run Code Online (Sandbox Code Playgroud)

.c:

struct singleton
{
    char sharedData[256];
};

struct singleton* get_instance()
{
    static struct singleton* instance = NULL;

    if (instance == NULL)
    {
        //do initialization here
    }

    return instance;
}
Run Code Online (Sandbox Code Playgroud)