虽然设计模式最初是为面向对象编程(OOP)语言(如 Java 或 C++)设计的,但许多设计模式的思想也可以应用于非面向对象的语言,如 C 语言。虽然 C 语言本身不支持类和对象的概念,但可以通过函数指针、结构体和其他技巧来模拟面向对象的特性。
下面我将介绍几个常见的设计模式,并给出 C 语言的例子。
1. 工厂模式(Factory Pattern)
工厂模式提供了一个创建对象的接口,但允许子类决定实例化哪一个类。工厂模式使得一个类的实例化延迟到了子类。
示例代码
c
深色版本
1#include <stdio.h>
2#include <stdlib.h>
3
4typedef struct {
5 void (*print)(const char *);
6} Printer;
7
8void printToConsole(const char *message) {
9 printf("Printing to console: %s\n", message);
10}
11
12void printToFile(const char *message) {
13 printf("Printing to file: %s\n", message);
14}
15
16Printer* createConsolePrinter() {
17 Printer* printer = (Printer*)malloc(sizeof(Printer));
18 printer->print = printToConsole;
19 return printer;
20}
21
22Printer* createFilePrinter() {
23 Printer* printer = (Printer*)malloc(sizeof(Printer));
24 printer->print = printToFile;
25 return printer;
26}
27
28int main() {
29 Printer* consolePrinter = createConsolePrinter();
30 Printer* filePrinter = createFilePrinter();
31
32 consolePrinter->print("Hello, Console!");
33 filePrinter->print("Hello, File!");
34
35 free(consolePrinter);
36 free(filePrinter);
37
38 return 0;
39}
2. 单例模式(Singleton Pattern)
单例模式确保一个类只有一个实例,并提供一个全局访问点来访问这个实例。
示例代码
c
深色版本
1#include <stdio.h>
2#include <stdlib.h>
3#include <pthread.h>
4
5typedef struct {
6 int data;
7} Singleton;
8
9static Singleton* singletonInstance = NULL;
10static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
11
12Singleton* getSingletonInstance() {
13 pthread_mutex_lock(&mutex);
14 if (!singletonInstance) {
15 singletonInstance = (Singleton*)malloc(sizeof(Singleton));
16 singletonInstance->data = 42;
17 }
18 pthread_mutex_unlock(&mutex);
19 return singletonInstance;
20}
21
22void singletonFunction() {
23 Singleton* instance = getSingletonInstance();
24 printf("Singleton data: %d\n", instance->data);
25}
26
27int main() {
28 Singleton* instance1 = getSingletonInstance();
29 Singleton* instance2 = getSingletonInstance();
30
31 singletonFunction();
32
33 // 注意:在 C 中,你需要手动释放内存
34 free(instance1);
35 free(instance2);
36
37 return 0;
38}
3. 观察者模式(Observer Pattern)
观察者模式定义了对象间的一种一对多依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都会得到通知并自动更新。
示例代码
c
深色版本
1#include <stdio.h>
2#include <stdlib.h>
3#include <string.h>
4
5typedef struct {
6 void (*update)(const char *);
7} Observer;
8
9typedef struct {
10 Observer* observers[10];
11 int count;
12} Subject;
13
14void addObserver(Subject* subject, Observer* observer) {
15 if (subject->count < 10) {
16 subject->observers[subject->count++] = observer;
17 }
18}
19
20void notifyObservers(Subject* subject, const char *message) {
21 for (int i = 0; i < subject->count; i++) {
22 subject->observers[i]->update(message);
23 }
24}
25
26void updateObserverA(const char *message) {
27 printf("Observer A received: %s\n", message);
28}
29
30void updateObserverB(const char *message) {
31 printf("Observer B received: %s\n", message);
32}
33
34int main() {
35 Subject subject = {NULL, 0};
36
37 Observer observerA = {updateObserverA};
38 Observer observerB = {updateObserverB};
39
40 addObserver(&subject, &observerA);
41 addObserver(&subject, &observerB);
42
43 notifyObservers(&subject, "Notification from subject");
44
45 return 0;
46}
4. 策略模式(Strategy Pattern)
策略模式定义了一系列算法,并将每个算法封装起来,使它们可以互相替换。策略模式让算法的变化独立于使用算法的客户端。
示例代码
c
深色版本
1#include <stdio.h>
2#include <stdlib.h>
3
4typedef struct {
5 void (*sort)(int *, int);
6} SortingStrategy;
7
8void bubbleSort(int *array, int size) {
9 int i, j, temp;
10 for (i = 0; i < size - 1; i++)
11 for (j = 0; j < size - i - 1; j++)
12 if (array[j] > array[j + 1]) {
13 temp = array[j];
14 array[j] = array[j + 1];
15 array[j + 1] = temp;
16 }
17}
18
19void quickSort(int *array, int size) {
20 // Quick sort implementation can be here
21 printf("Sorting using quick sort.\n");
22}
23
24SortingStrategy* createBubbleSortStrategy() {
25 SortingStrategy* strategy = (SortingStrategy*)malloc(sizeof(SortingStrategy));
26 strategy->sort = bubbleSort;
27 return strategy;
28}
29
30SortingStrategy* createQuickSortStrategy() {
31 SortingStrategy* strategy = (SortingStrategy*)malloc(sizeof(SortingStrategy));
32 strategy->sort = quickSort;
33 return strategy;
34}
35
36int main() {
37 int arr[] = {5, 2, 9, 1, 5, 6};
38 int n = sizeof(arr) / sizeof(arr[0]);
39
40 SortingStrategy* bubbleSortStrategy = createBubbleSortStrategy();
41 SortingStrategy* quickSortStrategy = createQuickSortStrategy();
42
43 bubbleSortStrategy->sort(arr, n);
44 quickSortStrategy->sort(arr, n);
45
46 free(bubbleSortStrategy);
47 free(quickSortStrategy);
48
49 return 0;
50}
总结
尽管 C 语言不是面向对象的语言,但通过函数指针、结构体等手段,依然可以实现类似于面向对象设计模式的功能。以上四个例子展示了如何在 C 语言中实现一些常见的设计模式。需要注意的是,在 C 语言中,内存管理需要手动完成,这一点与面向对象语言有所不同。