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

    单例模式

    <?php
    
    class Single
    {
        private $name;//声明一个私有的实例变量
    
        private function __construct()
        {
            //声明私有构造方法为了防止外部代码使用new来创建对象。
        }
    
        static public $instance;//声明一个静态变量(保存在类中唯一的一个实例)
    
        static public function getinstance()
        {//声明一个getinstance()静态方法,用于检测是否有实例对象
            if (!self::$instance) {
                self::$instance = new self();
            }
            return self::$instance;
        }
    
        public function setname($n)
        {
            $this->name = $n;
        }
    
        public function getname()
        {
            return $this->name;
        }
    }
    
    
    $oa = Single::getinstance();
    $ob = Single::getinstance();
    $oa->setname('hello world');
    $ob->setname('good morning');
    echo $oa->getname();//good morning
    echo $ob->getname();//good morning
    
    Class Person
    {
        private $name;
    
        private function __construction()
        {
            //防止new
        }
    
        static public $instance;
    
        /**
         * @return mixed
         */
        public static function getInstance()
        {
            if (!self::$instance) {
                self::$instance = new self;
            }
            return self::$instance;
        }
    
        public function setName($name)
        {
            $this->name = $name;
        }
    
        /**
         * @return mixed
         */
        public function getName()
        {
            return $this->name;
        }
    
    }
    
    $in = Person::$instance;
    var_dump($in);
    $p1 = Person::getInstance();
    $p1->setName('dddd');
    $p2 = Person::getInstance();
    $p2->setName('333  ');
    echo $p1->getName();
    echo $p2->getName();
    
  • 相关阅读:
    习题2-7
    习题2-6
    习题2-5
    习题2-4
    习题2-3
    作业二 分支循环结构
    2- 8
    实验三-计算圆柱体积
    实验三-计算n个圆柱体体积
    实验3-计算圆面积
  • 原文地址:https://www.cnblogs.com/cs88/p/6344937.html
Copyright © 2011-2022 走看看