分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 前端开发

设计模式之空对象模式(php实现)

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

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

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

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

<?phpnamespace 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 (空对象代替类)

<?phpnamespace 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 (用户工厂类)

<?phpnamespace 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

<?phpspl_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/>‘;

设计模式之空对象模式(php实现)

原文地址:https://www.cnblogs.com/zhouqi666/p/9166315.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved