单例模式的简单总结:
一、static变量的复习(明白为啥不用static全局变量,而是用单例模式)
When modifying a variable, the static keyword specifies that the variable has static duration (it is allocated when the program begins and deallocated when the program ends) and initializes it to 0 unless another value is specified. When modifying a variable or function at file scope, the static keyword specifies that the variable or function has internal linkage (its name is not visible from outside the file in which it is declared). A variable declared static in a function retains its state between calls to that function. When modifying a data member in a class declaration, the static keyword specifies that one copy of the member is shared by all instances of the class. When modifying a member function in a class declaration, the static keyword specifies that the function accesses only static members. Static data members of classes must be initialized at file scope. In recursive code, a static object or variable is guaranteed to have the same state in different instances of a block of code. The members of a union cannot be declared as static. An anonymous union declared globally must be explicitly declared static. Objects and variables defined outside all blocks have static lifetime and external linkage by default. A global object or variable that is explicitly declared as statichas internal linkage.
二、单件模式
确保类只有一个实例,并提供全局访问点。延迟实例化。 多线程可能会创建多个实例,因此应该加入同步方法,但是同步一个方法,会带来程序执行效率下降100倍。
办法:
1.急切方式:静态成员初始化的时候实例化,这样在加载这个类的时候就会创建此单例。private static A* instance = new A();
2.双重检查加锁。使用volatile 变量.volatile变量保证编译的时候不做优化,这样这样读取变量就不是从寄存器,而是从原始的内存中读取最新的值。确保在第一次创建实例才执行同步方法。以后直接引用这个对象不需要同步的控制。
3.同步实例方法。如果不频繁调用这个返回实例方法的话,不会影响程序性能的话。
三、 问题:在c++中同步是怎么实现的呢?在java中用synchronized,c++中我尚未可知,可否有人告知?