空对象模式(Null Object Pattern)
在空对象模式(Null Object Pattern)中,一个空对象取代 NULL 对象实例的检查。Null 对象不是检查空值,而是反应一个不做任何动作的关系。这样的 Null 对象也可以在数据不可用的时候提供默认的行为。
在空对象模式中,我们创建一个指定各种要执行的操作的抽象类和扩展该类的实体类,还创建一个未对该类做任何实现的空对象类,该空对象类将无缝地使用在需要检查空值的地方。
示例代码:
<?php
abstract class AbstractCustomer{
protected $name;
abstract function getName();
abstract function isNil();
}
class RealCustomer extends AbstractCustomer{
function __construct($name){
$this->name=$name;
}
function getName(){
return $this->name;
}
function isNil(){
return false;
}
}
class NullCustomer extends AbstractCustomer{
function getName(){
return "not available in Customer Database";
}
function isNil(){
return true;
}
}
class CustomerFactory{
static $nameList=['Rob','Joe','Julie'];
static function getCustomer($name){
if(in_array($name, self::$nameList)){
return new RealCustomer($name);
}
//使用返回空对象代替NULL异常处理
return new NullCustomer;
}
}
function main(){
//测试名字:Rob,Joe,Julie,Jim
$customer=CustomerFactory::getCustomer('Joe');
//因为这边的代码是直接调用getName(),所以$customer不能为null对象
//这是设计NullCustomer的目的
echo $customer->getName();
echo PHP_EOL;
$customer=CustomerFactory::getCustomer('Jim');
echo $customer->getName();
echo PHP_EOL;
}main();
结果显示:
Joe
not available in Customer Database