PS:原创文章,如需转载,请注明出处,谢谢!
本文地址:http://flyer0126.iteye.com/blog/1502576
/**
* 单例模式实现类-->ArrayAccess(数组式访问)接口
*
* @author flyer0126
* @since 2012/4/27
*/
class Single{
private $name;
private static $_Instance = null;
private function __construct()
{
}
static function load()
{
if(null == self::$_Instance)
{
self::$_Instance = new Single();
}
return self::$_Instance;
}
public function setName($name)
{
$this->name = $name;
}
public function getName()
{
return $this->name;
}
}
$s = Single::load();
$s->setName("jack");
echo $s->getName(); //jack
// 调整一下(继承ArrayAccess && 实现4个方法)
class Single implements ArrayAccess
{
private $name;
private static $_Instance = null;
private function __construct()
{
}
static function load()
{
if(null == self::$_Instance)
{
self::$_Instance = new Single();
}
return self::$_Instance;
}
public function setName($name)
{
$this->name = $name;
}
public function getName()
{
return $this->name;
}
/**
* 实现四个方法
* offsetExists(),用于标识一个元素是否已定义
* offsetGet(),用于返回一个元素的值
* offsetSet(),用于为一个元素设置新值
* offsetUnset(),用于删除一个元素和相应的值
**/
public function offsetSet($offset, $value)
{
if (is_null($offset))
{
$this->container[] = $value;
}
else
{
$this->container[$offset] = $value;
}
}
public function offsetGet($offset)
{
return isset($this->container[$offset]) ? $this->container[$offset] : null;
}
public function offsetExists($offset)
{
return isset($this->container[$offset]);
}
public function offsetUnset($offset)
{
unset($this->container[$offset]);
}
}
$s = Single::load();
$s->setName("jack");
$s["name"] = "mike";
echo $s->getName(); //jack
echo $s["name"]; //mike
print_r($s);
/**
Single Object
(
[name:Single:private] => jack
[container] => Array
(
[name] => mike
)
)
**/
后述:
ArrayAccess(数组式访问)接口 提供像访问数组一样访问对象的能力的接口。
OO实现逻辑的封装,而当这种封装对我们已有的逻辑调用方式产生变更时,可以利用这种方式进行巧妙转变。