- 单例模式
单例模式确保一个类只有一个实例,并提供一个全局访问点。
通俗解释:想象一个公司只能有一个CEO。无论你如何尝试创建新的CEO,你总是会得到同一个人。
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int data;
} Singleton;
static Singleton* instance = NULL;
Singleton* getInstance() {
if (instance == NULL) {
instance = (Singleton*)malloc(sizeof(Singleton));
instance->data = 0;
}
return instance;
}
int main() {
Singleton* s1 = getInstance();
Singleton* s2 = getInstance();
s1->data = 5;
printf("s2->data = %d\n", s2->data);
return 0;
}
- 工厂模式
工厂模式提供了一种将对象的实例化过程委托给子类的方法。
通俗解释:想象一个披萨店。你只需告诉店员你想要什么类型的披萨(比如"蘑菇披萨"),店员就会为你制作。你不需要知道具体是如何制作的。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
char name[20];
} Pizza;
Pizza* createPizza(const char* type) {
Pizza* pizza = (Pizza*)malloc(sizeof(Pizza));
if (strcmp(type, "cheese") == 0) {
strcpy(pizza->name, "Cheese Pizza");
} else if (strcmp(type, "pepperoni") == 0) {
strcpy(pizza->name, "Pepperoni Pizza");
} else {
strcpy(pizza->name, "Unknown Pizza");
}
return pizza;
}
int main() {
Pizza* cheesePizza = createPizza("cheese");
Pizza* pepperoniPizza = createPizza("pepperoni");
printf("%s\n", cheesePizza->name);
printf("%s\n", pepperoniPizza->name);
free(cheesePizza);
free(pepperoniPizza);
return 0;
}
- 观察者模式
观察者模式定义了对象之间的一对多依赖关系,当一个对象改变状态时,它的所有依赖者都会收到通知并自动更新。
通俗解释:想象你订阅了一个YouTube频道。每当频道上传新视频时,你就会收到通知。你是观察者,YouTube频道是被观察的对象。
#include <stdio.h>
#include <stdlib.h>
#define MAX_OBSERVERS 10
typedef struct Subject Subject;
typedef struct Observer Observer;
struct Observer {
void (*update)(Observer*, int);
};
struct Subject {
Observer* observers[MAX_OBSERVERS];
int observerCount;
int state;
};
void initSubject(Subject* subject) {
subject->observerCount = 0;
subject->state = 0;
}
void addObserver(Subject* subject, Observer* observer) {
if (subject->observerCount < MAX_OBSERVERS) {
subject->observers[subject->observerCount++] = observer;
}
}
void notifyObservers(Subject* subject) {
for (int i = 0; i < subject->observerCount; i++) {
subject->observers[i]->update(subject->observers[i], subject->state);
}
}
void setState(Subject* subject, int state) {
subject->state = state;
notifyObservers(subject);
}
void update(Observer* observer, int state) {
printf("Observer received update. New state: %d\n", state);
}
int main() {
Subject subject;
initSubject(&subject);
Observer observer1 = {update};
Observer observer2 = {update};
addObserver(&subject, &observer1);
addObserver(&subject, &observer2);
setState(&subject, 5);
return 0;
}