1
+ #include "../src/func.h"
2
+
3
+ int main (void )
4
+ {
5
+ printf ("test start:\r\n" );
6
+ /**
7
+ * 单例模式就是一个类只创建一个实例,以便节省开销和保证统一
8
+ * 对于多线程语言需要注意线程安全和性能之间取得一个平衡
9
+ */
10
+
11
+ // 懒汉模式,调用函数时实例化
12
+ LazySingleton * lazy_singleton1 = get_lazy_singleton_instance ("lazySingleton1" );
13
+ LazySingleton * lazy_singleton2 = get_lazy_singleton_instance ("lazySingleton2" );
14
+ lazy_singleton1 -> run (lazy_singleton1 );
15
+ // 实例相同
16
+ lazy_singleton2 -> value = 99 ;
17
+ lazy_singleton2 -> run (lazy_singleton2 );
18
+
19
+ // 懒汉模式,线程安全
20
+ LazySingletonSafe * lazy_singleton_safe1 = get_lazy_singleton_safe_instance ("lazySingletonSafe1" );
21
+ LazySingletonSafe * lazy_singleton_safe2 = get_lazy_singleton_safe_instance ("lazySingletonSafe2" );
22
+ lazy_singleton_safe1 -> run (lazy_singleton_safe1 );
23
+ // 实例相同
24
+ lazy_singleton_safe2 -> value = 88 ;
25
+ lazy_singleton_safe2 -> run (lazy_singleton_safe2 );
26
+
27
+ // 懒汉模式volatile,线程安全
28
+ LazySingletonVolatile * lazy_singleton_volatile1 = get_lazy_singleton_volatile_instance ("lazySingletonVolatile1" );
29
+ LazySingletonVolatile * lazy_singleton_volatile2 = get_lazy_singleton_volatile_instance ("lazySingletonVolatile2" );
30
+ lazy_singleton_volatile1 -> run (lazy_singleton_volatile1 );
31
+ // 实例相同
32
+ lazy_singleton_volatile2 -> value = 77 ;
33
+ lazy_singleton_volatile2 -> run (lazy_singleton_volatile2 );
34
+
35
+ // 饿汉模式,已经初始化,可直接使用
36
+ EagerSingleton * eager_singleton1 = get_eager_singleton_instance ("eagerSingleton1" );
37
+ EagerSingleton * eager_singleton2 = get_eager_singleton_instance ("eagerSingleton2" );
38
+ eager_singleton1 -> run (eager_singleton1 );
39
+ // 实例相同
40
+ eager_singleton2 -> run (eager_singleton2 );
41
+ }
42
+
43
+ /**
44
+ jarry@jarrys-MacBook-Pro c % gcc test/test.c ./src下*.c
45
+ jarry@jarrys-MacBook-Pro c % ./a.out
46
+ test start:
47
+
48
+ proxy_image_constructor() [构建ProxyImage]
49
+ ProxyImage::display() [file_name=001.jpg]
50
+ real_image_constructor() [构建RealImage]
51
+ RealImage::load_from_disk() [file_name=001.jpg]
52
+ RealImage::display() [file_name=001.jpg]
53
+ ProxyImage::display() [file_name=001.jpg]
54
+ RealImage::display() [file_name=001.jpg]%
55
+ */
0 commit comments