面向对象

<?php
header("Content-Type:text/html; charset=UTF-8");
/*
* [单例模式]
* 单例模式也叫单态模式
* 可以保证,一个类只能有一个对象实例;
* 实现要点
* ①构造函数私有化,不允许使用new关键字创建对象;
* ②对外提供获取对戏那个的方法.在方法中判断对象是否为空,如果为空则创建对象并返回,如果不为空
* 则直接返回;
* ③实例对象的属性以及获取对象的方法必须都是静态的。
* ④之后,创建对象只能使用我们提供的静态方法。 $s1 = Singleton::getInstance();
* */

class Singleton{
static private $single = null;
private function __construct(){}//构造函数私有化,不允许使用new关键字创建对象
static function getInstance(){
if(!self::$single){// !(self::$Single instanceof self)
self::$single = new Singleton();//Singleton也可用self代替
}
return self::$single;
}

function __destruct(){
echo "被销毁<br/>";
}

}

Singleton::getInstance();
Singleton::getInstance();
Singleton::getInstance();

posted @ 2017-06-11 21:19  赵娜  阅读(88)  评论(0编辑  收藏  举报