• PHP设计模式之单例模式


    单例模式(Singleton pattern)是一种创建型模式,它会限制应用程序,使其只能创建某个类类型的单一实例。举例来说,一个Web站点将会需要一个数据库连接对象,但是应该有且只有一个,因此我们需要使用单例模式来实现。

    eg:

    <?php
    class Config{
        static private $_instance = null; //确保对于一个特定类来说只存在一个单一的实例
        private $_settings = array();
        
        private function __construct(){}//防止new出来一个新实例
        private function __clone(){} //防止clone来创建一个新实例
    
        static funcitn getInstance(){
              if(self::$_instance == null){
                  self::$_instance = new Config();
              }
              return self::$_instance;
        }
    
        function set($index, $value){
             $this->_settings[$index] = $value;
       }
    
        function get($index){
              return $this->_settings[$index];
        }
    }
    ?>

    使用Config类

    创建config类

    $CONFIG = Config::getInstance();

    如果这个对象是这个类的第一个对象,那么将会创建一个新的类的实例,并且赋值给内部的私有属性$_instance,并且返回结果。否则使用同一个实例返回

  • 相关阅读:
    Linux改主机名最简单方法
    while 循环
    Appium UI自动化的那些梗
    常量函数、常量引用参数、常量引用返回值[C++]
    常量指针和指针常量的区别
    XHProf中文手册
    xhprof学习笔记
    C语言中内存操作函数
    DRF源码剖析——视图
    2020CCPC秦皇岛 k Kingdom’s Power
  • 原文地址:https://www.cnblogs.com/ShowJoy/p/3747935.html
Copyright © 2020-2023  润新知