Generally speaking, there is a one-to-many relationship between classes and objects (instances of classes). But in some cases, we only need one instance of a class. For example, the diversity of multiple instances will bring about some uncontrollable factors. Multiple instantiations are a waste of resources and reduce efficiency; another example is that they are factory objects (factory objects), used to create systems. other objects in , etc. At this time, a better way to deal with it is to make the instances of the class
single: ensure that this class generates at most one instance during operation (Singleton mode), or make all instances consistent (Monostate mode).
Example of Singleton mode implemented under PHP:
<?php classSingleton { privatestatic$instance; privatefunction__construct() { } publicstaticfunctioninstance() { if(self::$instance==null) { self::$instance=newSingleton(); } returnself::$instance; } } ?>
$instance=Singleton::instance(); // 这样是错误的: $instance = new Singleton();
A detailed analysis of the characteristics of the singleton mode implemented under PHP:
1. A static, private attribute: used Save an instance. Static ensures that the class will not be instantiated and can also be called by class methods. Private ensures that it will not be changed by instances of the class.
2. A private constructor: This class is not allowed to be instantiated outside this class.
3. A static, public method: responsible for creating instances and ensuring their uniqueness. static allows the method to be called without being instantiated.
2. It can be derived and created. Given a class, you can create a singleton subclass of it.
2. The use is opaque, the user must know that it uses a singleton class and cannot be instantiated through
new.
The basic principle of the monostate pattern is to make all instances of the monostate class use the same instance. In fact, all attributes of the class can be declared static:
<?php classmonostate { privatestatic$itsX=0; publicfunction__construct() { } publicfunctionsetX($x) { self::$itsX=$x; } publicfunctiongetX() { returnself::$itsX; } } ?>
The above is the content of implementing Singleton mode and Monostate mode in PHP. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!