github地址:https://github.com/ZQCard/design_pattern
/**
* 在空对象模式(Null Object Pattern)中,一个空对象取代 NULL 对象实例的检查。
* Null 对象不是检查空值,而是反应一个不做任何动作的关系。这样的 Null 对象也可以在数据不可用的时候提供默认的行为。
* 在空对象模式中,我们创建一个指定各种要执行的操作的抽象类和扩展该类的实体类,还创建一个未对该类做任何实现的空对象类,该空对象类将无缝地使用在需要检查空值的地方。
*/

(1)AbstractCustomer.class.php(抽象父类)

<?php

namespace NullObject;

abstract class AbstractCustomer
{
protected $name; public abstract function isNil():bool; public abstract function getName() : string;
}

(2)RealCustomer.class.php (真实用户类)

<?php

namespace NullObject;

class RealCustomer extends AbstractCustomer
{
public function __construct(string $name)
{
$this->name = $name;
} public function isNil():bool
{
return false;
} public function getName() : string
{
return $this->name;
}
}

(3)NullCustomer.class.php (空对象代替类)

<?php

namespace NullObject;

class NullCustomer extends AbstractCustomer
{
public function getName() : string
{
return "Not Available in Customer Database";
} public function isNil():bool
{
return true;
}
}

(4)CustomerFactory.class.php (用户工厂类)

<?php

namespace NullObject;

class CustomerFactory
{
public static $users = []; public static function getCustomer($name)
{
if (in_array($name, self::$users)){
return new RealCustomer($name);
}
return new NullCustomer();
}
}

(5)nullObject.php

<?php

spl_autoload_register(function ($className){
$className = str_replace('\\','/',$className);
include $className.".class.php";
}); use NullObject\CustomerFactory; CustomerFactory::$users = ["Rob", "Joe", "Julie"]; $customer1 = CustomerFactory::getCustomer('Rob');
$customer2 = CustomerFactory::getCustomer('Bob');
$customer3 = CustomerFactory::getCustomer('Joe');
$customer4 = CustomerFactory::getCustomer('Julie'); echo $customer1->getName();
echo '<br/>'; echo $customer2->getName();
echo '<br/>'; echo $customer3->getName();
echo '<br/>'; echo $customer4->getName();
echo '<br/>';

最新文章

  1. JQuery插件定义
  2. chrome中hack解决input:-webkit-autofill自定义样式
  3. Marathon
  4. BT3入门之中文语言支持
  5. java学习笔记(二)之数据部分
  6. 个人思考:能否sub.prototye=sup.prototype实现继承
  7. NAT(NAPT)地址转换过程
  8. House Robber II——Leetcode
  9. 修改mysql的默认字符集
  10. thinkphp 实现微信公众号开发(一)
  11. [转载] FreeMarker教程
  12. Asp.net Mvc 与 Web Api生命周期对比
  13. Kafka集群的搭建
  14. 用powershell实现自动化操作
  15. Java - 31 Java 发送邮件
  16. android AlertDialog.Builder
  17. Vue 需要使用jsonp解决跨域时,可以使用(vue-jsonp)
  18. GearCase UI - 自己构建一套基于 Vue 的简易开源组件库
  19. Oracle shared server模式连接ORA-12519
  20. MySQL导数据工具对比

热门文章

  1. python os操作
  2. 在LinkedIn的 Kafka 生态系统
  3. BZOJ2208 [Jsoi2010]连通数 【图的遍历】
  4. ZCC loves cube(cube)
  5. 解决某些PC站在手机端宽度显示不正常的问题
  6. angular.extend(dst,src)的简单示例
  7. linux mint 自动挂载windows的D盘和E盘
  8. .com和.cn域名的区别所在,各个域名后缀含义
  9. Js String 属性扩展
  10. ios 改变图片大小缩放方法