zoukankan      html  css  js  c++  java
  • 单例模式

    1、模式定义

    简单说来,单例模式的作用就是保证在整个应用程序的生命周期中,任何一个时刻,单例类的实例都只存在一个,同时这个类还必须提供一个访问该类的全局访问点。

    常见使用实例:数据库连接器;日志记录器(如果有多种用途使用多例模式);锁定文件。

    2、示例代码

    <?php
    
    namespace DesignPatternsCreationalSingleton;
    
    /**
     * Singleton类
     */
    class Singleton
    {
        /**
         * @var Singleton reference to singleton instance
         */
        private static $instance;
        
        /**
         * 通过延迟加载(用到时才加载)获取实例
         *
         * @return self
         */
        public static function getInstance()
        {
            if (null === static::$instance) {
                static::$instance = new static;
            }
    
            return static::$instance;
        }
    
        /**
         * 构造函数私有,不允许在外部实例化
         *
         */
        private function __construct()
        {
        }
    
        /**
         * 防止对象实例被克隆
         *
         * @return void
         */
        private function __clone()
        {
        }
    
        /**
         * 防止被反序列化
         *
         * @return void
         */
        private function __wakeup()
        {
        }
    }

    3、测试代码

    <?php
    
    namespace DesignPatternsCreationalSingletonTests;
    
    use DesignPatternsCreationalSingletonSingleton;
    
    /**
     * SingletonTest用于测试单例模式
     */
    class SingletonTest extends PHPUnit_Framework_TestCase
    {
    
        public function testUniqueness()
        {
            $firstCall = Singleton::getInstance();
            $this->assertInstanceOf('DesignPatternsCreationalSingletonSingleton', $firstCall);
            $secondCall = Singleton::getInstance();
            $this->assertSame($firstCall, $secondCall);
        }
    
        public function testNoConstructor()
        {
            $obj = Singleton::getInstance();
    
            $refl = new ReflectionObject($obj);
            $meth = $refl->getMethod('__construct');
            $this->assertTrue($meth->isPrivate());
        }
    }
  • 相关阅读:
    Blob
    MySQL This function has none of DETERMINISTIC, NO SQL...错误1418 的原因分析及解决方法 (转)
    事务--存储过程
    JDBC-Mysql-编译预处理(占位符)
    socket
    GUI---深度复制
    串行化--深度复制
    RESTful理解
    django中文和时区的配置
    redis-server报错
  • 原文地址:https://www.cnblogs.com/webclz/p/10731575.html
Copyright © 2011-2022 走看看