场景是:Jack 和 Mary 都想骑一个共享单车,但是单车只有一辆。一人能骑上单车的条件是现在单车没人使用。参考代码( php 版本):
<?php
/*
* 单例模式示例
*/
error_reporting(E_ALL);
ini_set('display_errors','on');
//
class SingletonBike{
private static $instance = null; //创建静态私有的变量保存该类对象
private $ownerUser = "";//使用者姓名
//构造函数私有化,防止直接创建对象
private function __construct($ownerUser) {
$this ->ownerUser = $ownerUser;
}
//构造函数私有化,防止直接创建对象
//防止克隆对象
private function __clone() {
}
//静态方法,创建实例
public static function getInstance($ownerUser){
if(!self::$instance instanceof self){//self 指类,this 代表实例,这里指代静态属性,使用 self
self::$instance = new self($ownerUser);
return self::$instance;
}else{
return null;
}
}
public function getOwnerUser(){
return $this->ownerUser;
}
//静态方法,销毁实例
public static function destroyInstance(){
self::$instance = null;
}
}
$singletonBike = SingletonBike::getInstance("Mary");
echo $singletonBike->getOwnerUser()."<br/>";//Mary
$singletonBike2 = SingletonBike::getInstance("Jack");
var_dump($singletonBike2);//null
echo "<br/>";
SingletonBike::destroyInstance();
$singletonBike2 = SingletonBike::getInstance("Jack");
var_dump($singletonBike2);//object(SingletonBike)#1 (1) { ["ownerUser":"SingletonBike":private]=> string(4) "Jack" }
echo "<br/>";
echo $singletonBike->getOwnerUser()."<br/>";//理想是为 Jack,结果为 Mary
?>
理论上希望最后的$singletonBike 不存在了,或者$singletonBike->getOwnerUser()的结果为 Jack。这样就证明 SingletonBike 的实例已经被销毁了。但是结果并没有。想请朋友帮忙想一个单例生成实例后销毁该实例的办法。谢谢。
<?php
/*
* 单例模式示例
*/
error_reporting(E_ALL);
ini_set('display_errors','on');
//
class SingletonBike{
private static $instance = null; //创建静态私有的变量保存该类对象
private $ownerUser = "";//使用者姓名
//构造函数私有化,防止直接创建对象
private function __construct($ownerUser) {
$this ->ownerUser = $ownerUser;
}
//构造函数私有化,防止直接创建对象
//防止克隆对象
private function __clone() {
}
//静态方法,创建实例
public static function getInstance($ownerUser){
if(!self::$instance instanceof self){//self 指类,this 代表实例,这里指代静态属性,使用 self
self::$instance = new self($ownerUser);
return self::$instance;
}else{
return null;
}
}
public function getOwnerUser(){
return $this->ownerUser;
}
//静态方法,销毁实例
public static function destroyInstance(){
self::$instance = null;
}
}
$singletonBike = SingletonBike::getInstance("Mary");
echo $singletonBike->getOwnerUser()."<br/>";//Mary
$singletonBike2 = SingletonBike::getInstance("Jack");
var_dump($singletonBike2);//null
echo "<br/>";
SingletonBike::destroyInstance();
$singletonBike2 = SingletonBike::getInstance("Jack");
var_dump($singletonBike2);//object(SingletonBike)#1 (1) { ["ownerUser":"SingletonBike":private]=> string(4) "Jack" }
echo "<br/>";
echo $singletonBike->getOwnerUser()."<br/>";//理想是为 Jack,结果为 Mary
?>
理论上希望最后的$singletonBike 不存在了,或者$singletonBike->getOwnerUser()的结果为 Jack。这样就证明 SingletonBike 的实例已经被销毁了。但是结果并没有。想请朋友帮忙想一个单例生成实例后销毁该实例的办法。谢谢。