单例模式的简单demo

来源:互联网 发布:淘宝上的订单险是什么 编辑:程序博客网 时间:2024/05/23 22:02

//C++版本(饿汉模式)

#include <iostream>

using namespace std;
class R
{
static R* instance;
R(){}
public:
static R* GetInstance()
{
return instance;
}


};
R* R::instance = new R;
/*
1.构造函数放在非public控制权限下
2.保证对象始终值存在一个(让对象始终存在于静态区)
3.对外部提供一个访问的接口
*/


int main()
{
R *a = R::GetInstance();
R *b = R::GetInstance();


if (a == b)
{
cout << "相等" << endl;
}
else
{
cout << "不相等" << endl;
}


return 0;

}

//php版本

<?php
class R
{
static $ins=null;
private function __construct()
{


}
static public function getins()
{
      if( ! (self::$ins instanceof self)){
            self::$ins= new self();
       }
      return self::$ins;
    }


}


$a=R::getins();
$b=R::getins();


if($a==$b)
{
echo "相等";
}
else
{
echo "不相等";
}
?>


0 0