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

    <?php
    /**
    * 单例模式实现
    */
    class Singleton
    {
    	//静态变量保存全局实例
    	private static $instance = null;
    
    	private function __clone()
    	{
    		//私有构造函数,防止外界实例化对象
    	}
    
    	private function __construct()
    	{
    		//私有克隆函数,防止外界克隆对象
    	}
    
    	//静态方法,单例统一访问入口
    	public static function getInstance()
    	{
    		if (self::$instance instanceof Singleton) {
    			echo "return exist instance
    ";
    			return self::$instance;
    		}
    		self::$instance = new Singleton();
    		echo "return new instance
    ";
    		return self::$instance;
    	}
    }
    
    $a = Singleton::getInstance();//output: return new instance
    $a = Singleton::getInstance();//output: return exist instance
    
  • 相关阅读:
    leetcode122
    leetcode121
    leetcode773
    leetcode803
    leetcode658
    leetcode723
    leetcode134
    leetcode340
    leetcode721
    leetcode362
  • 原文地址:https://www.cnblogs.com/clivewang/p/9869586.html
Copyright © 2011-2022 走看看