养浩然之气,活着不是为技术,请关心身边的人.
单件模式
上一篇 /
下一篇 2007-08-21 10:07:09
/ 个人分类:php设计模式介绍学习
class DbConn
{
/**
* static
property to hold singleton instance
*/
static
$instance = false;
/**
*
constructor
* private so
only getInstance() method can instantiate
* @return
void
*/
private
function __construct() {}
/**
* factory
method to return the singleton instance
* @return
DbConn
*/
public function
getInstance() {
if
(!DbConn::$instance) {
DbConn::$instance
= new DbConn;
}
return
DbConn::$instance;
}
}
Monostate Pattern(单态模式):类单件模式
有时候,我们需要这样一个类,所有类的实例都共享它的全局状态――换句话说,它所产生的任何实例返回严格一致的信息。class
ApplicationConfig {
var
$_state;
function
ApplicationConfig() {
$key =‘__stealth_singleton_state_index__’;
if
(!(array_key_exists($key, $GLOBALS)
&&
is_array($GLOBALS[$key]))) {
$GLOBALS[$key]
= array();
}
$this->_state
=& $GLOBALS[$key];
}
function
set($key, $val) {
$this->_state[$key]
= $val;
}
function
get($key) {
if
(array_key_exists($key, $this->_state)) {
return
$this->_state[$key];
}
}
这个技巧的核心是$this->state =& $GLOBALS[$key];
。在确定$GLOBALS[$key]是一个数组后,代码绑定一个全局数组的引用给类变量$this->state。从而,任何$this->state的改变都自然而言地同步到全局数组,包括类的其它实例。
导入论坛
收藏
分享给好友
管理
举报
TAG:
php设计模式介绍学习