我不想创造一个关于单身比静电更好,或者比全球更好的讨论,等等.我在SO上读了几十个关于类似主题的问题,但是我想不出这个具体问题的答案,所以我希望现在有人能用一个(或更多)real simple EXAMPLES个回答这个问题来启发我,而不仅仅是理论上的讨论.
在我的应用程序中,我有typical DB class to abstract the DB layer,可以在数据库上执行任务,而不必到处用代码mysql_connect / mysql_select_db / mysql...
编写
I could write the class either as a STATIC CLASS:个
class DB
{
private static $connection = FALSE; //connection to be opened
//DB connection values
private static $server = NULL; private static $usr = NULL; private static $psw = NULL; private static $name = NULL;
public static function init($db_server, $db_usr, $db_psw, $db_name)
{
//simply stores connections values, without opening connection
}
public static function query($query_string)
{
//performs query over alerady opened connection, if not open, it opens connection 1st
}
...
}
OR as a SINGLETON:个
class DBSingleton
{
private $inst = NULL;
private $connection = FALSE; //connection to be opened
//DB connection values
private $server = NULL; private $usr = NULL; private $psw = NULL; private $name = NULL;
public static function getInstance($db_server, $db_usr, $db_psw, $db_name)
{
//simply stores connections values, without opening connection
if($inst === NULL)
$this->inst = new DBSingleton();
return $this->inst;
}
private __construct()...
public function query($query_string)
{
//performs query over already opened connection, if connection is not open, it opens connection 1st
}
...
}
然后在我的应用程序中,如果我想查询数据库,我可以这样做
//Performing query using static DB object
DB:init(HOST, USR, PSW, DB_NAME);
DB::query("SELECT...");
//Performing query using DB singleton
$temp = DBSingleton::getInstance(HOST, USR, PSW, DB_NAME);
$temp->query("SELECT...");
对我来说,Singleton唯一的优势是避免将类的每个方法声明为static
.我相信你们中的一些人可以给我一个EXAMPLE分的单人版在这specific case分中的真正优势.提前谢谢您.