Singleton Mode
By providing access to its own shared instances, the singleton design mode is used to restrict the creation of a specific object only once.
Use Cases
For example, database instances generally adopt the singleton mode.
The Singleton mode can reduce class instantiation.
Code: Source InitPHP framework. First, check whether the class has been instantiated. If it is instantiated, use the object instance that has been stored in the static variable. If it is not instantiated, save the object.
[Php]
/**
* Core framework loading-all the classes of the framework must pass through this function.
* 1. Singleton Mode
* 2. class files in-Controller, Service, View, Dao, Util, and Library can be loaded.
* 3. The framework loads core functions.
* Usage: $ this-> load ($ class_name, $ type)
* @ Param string $ class_name Class Name
* @ Param string $ type category
*/Www.2cto.com
Public function load ($ class_name, $ type ){
$ Class_path = $ this-> get_class_path ($ class_name, $ type );
$ Class_name = $ this-> get_class_name ($ class_name );
If (! File_exists ($ class_path) InitPHP: initError ('file'. $ class_name. '. php is not exist! ');
If (! Isset (self: $ instance ['initphp'] [$ class_name]) {
Require_once ($ class_path );
If (! Class_exists ($ class_name) InitPHP: initError ('class'. $ class_name. 'is not exist! ');
$ Init_class = new $ class_name;
Self: $ instance ['initphp'] [$ class_name] = $ init_class;
}
Return self: $ instance ['initphp'] [$ class_name];
}
Author: initphp