单元素模式
单元素模式可以满足此要求。如果应用程序每次包含且仅包含一个对象,那么这个对象就 是一个单元素(Singleton),某些应用程序资源是独占的,因为有且只有一个此类型的资源。例如,通过数据库句柄到数据库的连接是独占的。您希望在应用程序中共享数据库句柄,因为在保持连接打开或关闭时,它是一种开销,在获取单个页面的过程中更是如此。
补
数据库句柄:根本上源于内存管理机制的问题—虚拟地址,简而言之数据的地址需要变动,变动以后就需要有人来记录管理变动,(就好像户籍管理一样),因此系统用句柄来记载数据地址的变更。其实设计机制很简单
:系统的某个部门移动了对象的地址后,同时上报给句柄所属部门管理者,管理者将改动写入句柄即可。再数据被重新起用时去其所属句柄内按内容存取即可
实例一
<?php
class DBConnect
{
static public $dbConnection = null;
function __construct()
{
self::$dbConnection = mysql_connect( "localhost", "root",
"youpassword" );
if ( mysql_errno() )
throw new Exception("Connect failed: " . mysql_error());
mysql_select_db( "zuitu_db", self::$dbConnection );
mysql_query( "SET NAMES UTF8;", self::$dbConnection );
}
}
class Singleton
{
public static function getUser()
{
static $dbUser = null;
if($dbUser == null)
$dbUser = new Singleton();
return $dbUser;
}
private $_handle = null;
private function __construct()
{
$emailid = 1;
$this->_handle = &
DBConnect::$dbConnection;
}
public function handle()
{
return $this->_handle;
}
}
$o = new DBConnect();
print_r(Singleton::getUser()->handle()."<br
/>");
print_r(Singleton::getUser()->handle()."<br
/>");
print_r(Singleton::getUser()->handle()."<br
/>");
print_r(Singleton::getUser()->handle()."<br
/>");
print_r(Singleton::getUser()->handle()."<br
/>");
print_r(Singleton::getUser()->handle()."<br
/>");
输出:Resource id #2
//输出的是一个资源id
Resource id
#2
Resource id
#2
Resource id
#2
Resource id
#2
Resource id
#2
实例二
多数的单元素模式在连接数据使用的时候为保证它的安全性是使用是内置到一个类里的
<?php
class DB
{
static private $mInstance = null;
static private $mConnection = null;
static public function &Instance()
{
if ( null == self::$mInstance )
{
$class = __CLASS__;
self::$mInstance = new $class;
}
return self::$mInstance;
}
function __construct()
{
self::$mConnection = mysql_connect( "localhost", "root",
"youpassword" );
if ( mysql_errno() )
throw new Exception("Connect failed: " . mysql_error());
@mysql_select_db( $name, self::$mConnection );
@mysql_query( "SET NAMES UTF8;", self::$mConnection );
}
static function GetLinkId() {
self::Instance();
return self::$mConnection;
}
function __destruct()
{
self::Close();
}
static public function Close()
{
if ( is_resource( self::$mConnection ) )
{
@mysql_close( self::$mConnection );