空对象模式(Null Object Pattern) - PHP示例

空对象模式(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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值