• 第二十一章 有些类也需要计划生育 --- 单例模式

    第二十一章 有些类也需要计划生育 --- 单例模式

    1. <?php
    2. class Singleton
    3. {
    4. private static $instance;
    5. private function __construct(){}
    6. public static function getInstance()
    7. {
    8. if (static::$instance == null)
    9. {
    10. static::$instance = new Singleton();
    11. }
    12. return static::$instance;
    13. }
    14. }
    15. //客户端代码
    16. $s1 = Singleton::getInstance();
    17. $s2 = Singleton::getInstance();
    18. if ($s1 == $s2)
    19. {
    20. echo "same class";
    21. }

    总结:

    单例模式,保证一个类仅有一个实例,并提供一个访问它的全局访问点。

    单例模式因为Singleton类封装它的唯一实例,这样它可以严格地控制客户怎样访问以及何时访问它。简单地说就是对唯一实例的受控访问。

    上一章:第二十章 想走?可以!先买票 --- 迭代器模式

    下一章:第二十二章 手机软件何时统一 --- 桥接模式