Singleton design pattern (single state)

/*

Singleton design pattern (single state)

定义: 一个类 只能允许有 一个对象存在.
1.不让进: 使类不能被实例化
2.留后门: 设置静态方法
3.给对象: 在静态方法里实例化该类
4.判初夜: 判断是否是 第一次产生该类的对象
5.设静态: 静态方法里 要使用静态属性

*/

/*//

1. Don't let in: make the class unable to be instantiated -----------------

class Test
{ // Set up a encapsulated construction method private function __construct() { //occupy, I just won’t let you NEW me~~~ } }*/





/*//

2.Leave the back door: set a static method--------------------

class Test
{ // Set up a encapsulated construction method private function __construct() { //occupy, I just won’t let you NEW me~~~ } //backdoor public static function getObject() { echo "Ah, I am a backdoor , Come in! ”; } }*/











/*//

3. To the object: instantiate the class in a static method ------------------

class Test
{ // Set up a encapsulated construction method private function __construct() { //occupy, I just won’t let you NEW me~~~ } //backdoor public static function getObject() { echo "Ah, I am a backdoor , Come in! ”; return new self();//Instantiate an object for you } }*/












/*//

4. Judging the first night: to determine whether it is the first time that this type of object is produced ------------------

class Test
{ private KaTeX parse error: Expected group after'_' at position 70: …ivate function _̲_construct()… this->obj === null) { $this->obj = new self();//Instantiate An object } //The property returned is actually the object return $this->obj; } }*/






//

5. Make static: static properties should be used in static methods ------------------

class Test
{ private static KaTeX parse error: Expected group after'_' at position 70: …ivate function _̲_construct()… obj === null) { self:: KaTeX parse error: Expected'EOF', got'}' at position 36: …Instantiate an object} ̲ //The returned attribute… obj; } }



/ Test::getObject();//Use a static method to access the method
exit in this class ;
/

$t1 = Test::getObject();
$t2 = Test::getObject();
$t3 = Test::getObject();
$t4 = Test::getObject();
$t5 = Test::getObject();
$t6 = Test::getObject();
$t7 = Test::getObject();
$t8 = Test::getObject();

// Determine whether two objects are the same object
if ($t1 === $t6) { echo "Oh, Yes! is the same instance "; } else { echo "Oh, No! Not the same instance "; }





Author: celibacy to be Chang Yen
link: https: //www.zhihu.com/question/35285158/answer/141024074
Source: know almost
copyrighted by the author. For commercial reprints, please contact the author for authorization, and for non-commercial reprints, please indicate the source.

Guess you like

Origin blog.csdn.net/weixin_43272542/article/details/113991059