How to use singleton objects in the C language?

In C language, there is no built-in concept of a singleton object, but the singleton pattern can be implemented through coding.

The purpose of the singleton pattern is to ensure that only one instance object is created in the program and to provide a global way to access that object.

Here is one common way to implement the Singleton pattern:

  1. Create a static variable to store a pointer to the singleton object.
  2. Create a function to fetch a singleton object. The function should check if a static variable has already been initialized, if so, it should return the value of the static variable; if not, it should create a new object, assign it to the static variable, and then return the object.
  3. Call the function to retrieve the singleton object’s pointer wherever it is needed.

For example, here is a simple example to implement the singleton pattern:

#include <stdio.h>

// 定义单例对象的结构体
typedef struct {
    int value;
} Singleton;

// 定义静态变量来保存单例对象的指针
static Singleton *singleton = NULL;

// 获取单例对象的函数
Singleton* getSingleton() {
    if (singleton == NULL) {
        // 如果静态变量未被初始化,则创建一个新的对象
        singleton = malloc(sizeof(Singleton));
        singleton->value = 0;
    }
    return singleton;
}

int main() {
    Singleton *obj1 = getSingleton();
    Singleton *obj2 = getSingleton();

    obj1->value = 10;
    printf("obj1 value: %d\n", obj1->value);
    printf("obj2 value: %d\n", obj2->value);

    return 0;
}

Output:

obj1 value: 10
obj2 value: 10

In this example, the getSingleton function is used to fetch a pointer to a singleton object. If the object has not been initialized yet, the function will create a new object and assign it to the static variable singleton. Each time the getSingleton function is called, it will return a pointer to the same object. Therefore, obj1 and obj2 point to the same object, and their value attributes will remain consistent.

bannerAds