单例模式的一点小疑问
程序员文章站
2022-03-16 15:35:12
...
最近在开始一些小项目,接触到单利模式,本着定义类的时候,尽可能的隐藏信息的原则,我对类进行了以下的编写
class openGate{
private $dbname='mysql:host=localhost;dbname=project';
private $username='root';
private $password='root';
private static $key=null;
private function __construct(){}
private function __clone(){}
public static function gateKey(){
if (self::$key==null) {
self::$key=new openGate();
return self::$key->gateWay();
}
return self::$key->gateway();
}
public function gateWay(){
return new PDO($this->dbname,$this->username,$this->password);
}
}
$person=openGate::gateKey();
var_dump($person);
请问一下,这样和以下相比
class openGate{
private static $key=null;
private function __construct(){}
private function __clone(){}
public static function gateKey(){
if (self::$key==null) {
$dbname='mysql:host=localhost;dbname=project';
$username='root';
$password='root';
return self::$key=new PDO($dbname,$username,$password);
}
return self::$key;
}
}
$person=openGate::gateKey();
var_dump($person);
有哪些优缺点,或者是只是单纯的多余呢?
回复内容:
最近在开始一些小项目,接触到单利模式,本着定义类的时候,尽可能的隐藏信息的原则,我对类进行了以下的编写
class openGate{
private $dbname='mysql:host=localhost;dbname=project';
private $username='root';
private $password='root';
private static $key=null;
private function __construct(){}
private function __clone(){}
public static function gateKey(){
if (self::$key==null) {
self::$key=new openGate();
return self::$key->gateWay();
}
return self::$key->gateway();
}
public function gateWay(){
return new PDO($this->dbname,$this->username,$this->password);
}
}
$person=openGate::gateKey();
var_dump($person);
请问一下,这样和以下相比
class openGate{
private static $key=null;
private function __construct(){}
private function __clone(){}
public static function gateKey(){
if (self::$key==null) {
$dbname='mysql:host=localhost;dbname=project';
$username='root';
$password='root';
return self::$key=new PDO($dbname,$username,$password);
}
return self::$key;
}
}
$person=openGate::gateKey();
var_dump($person);
有哪些优缺点,或者是只是单纯的多余呢?
你的改动,跟单例模式没有半毛钱关系
上一篇: java并发--全部线程机制实例详解
下一篇: python判断复数的基本步骤