Contains only a special class called a singleton class. The singleton mode guarantees that there is only one object for a class in the system.
Advantages:
1 provides controlled access to a unique instance.
2 Save memory, only one instance of the class exists in system memory .
3 to Prevent logic errors , such as generating serial numbers, two instances may produce two identical serial numbers.
4 Allow variable number of instances.
Disadvantages:
1 time overhead: Each request reference checks for the existence of an instance of the class and still requires time overhead to resolve by static initialization.
2 Development Confusion: developers need to remember that the Singleton class cannot be created with the New keyword.
3 Life cycle: memory-managed languages such as Java,. Net), only a singleton class can cause an instance to be deallocated because it contains a private reference to the instance, a language that can manually free memory (such as C + +), an object instance can be deleted, and a floating reference is easy to appear.
4 easy to extend: The singleton mode has no abstraction layer and is not easy to expand.
5 Negative issues: Save resources and set the database connection pool object to a singleton class, causing too many programs that share connection pool objects to overflow the connection pool .
6 Object loss: The instantiated object is not exploited for a long time , and in memory-managed languages, it is reclaimed by the system, causing the object state to be lost .
Realize:
1 private, static, member variable.
2 private construction methods, which cannot be created by the new keyword.
3 The private cloning method, so that the instance cannot be copied or cloned.
4 static initialization, the getinstance () method is static, and the time overhead is reduced.
PHP instance
Class Singleton{private Static $_instance = null;//private static variable __construct () {//Private constructor method, external cannot get instance of class by New//:} Private Function __clone () {}//-clone method, cannot be copied or cloned public static function getinstance () {//static method gets instance, reduces time consumption if (! ( Self::$_instance instanceof self) {self::_instance = new Singleton ();} return self::_instance;}}
1418131414
From Arcticfox
Design Pattern _ Singleton mode