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

    单例模式的定义:保证一个类只有一个实例,并提供一个访问它的全局访问点

    class Singleton
    {
        //创建静态私有的变量保存该类对象
        static private $instance;
    
        //防止使用new直接创建对象
        private function __construct(){}
    
        //防止使用clone克隆对象
        private function __clone(){}
    
        static public function getInstance()
        {
            //判断$instance是否是Singleton的对象,不是则创建
            if (!self::$instance instanceof self) {
                self::$instance = new self();
            }
            return self::$instance;
        }
    
        public function test()
        {
            echo "我是一个单例模式";
        }
    }
    
    $sing = Singleton::getInstance();
    $sing->test();
    $sing2 = new Singleton(); //Fatal error: Uncaught Error: Call to private Singleton::__construct() from invalid context in
    $sing3 = clone $sing; //Fatal error: Uncaught Error: Call to private Singleton::__clone() from context
    

      

  • 相关阅读:
    Linux的学习思路
    不错的文章
    【转】普通树转换成二叉树
    【转】高效阅读代码
    分组
    最大值
    运输计划
    [SDOI2007]游戏
    [SCOI2005]王室联邦
    10、Web Service-IDEA-jaxrs 整合spring
  • 原文地址:https://www.cnblogs.com/zh718594493/p/12090502.html
Copyright © 2011-2022 走看看