策略模式在PHP业务代码的实践

使用策略模式的缘由
此业务由于是要支持不同配置的预约,以及后期可能会有很多种类型的配置,而且不同类型的配置又完成不同,如果直接编码,后期的扩展性以及维护性会比较麻烦。
1.正常代码实现:

<?php public function makeReservation($mainkey){ $type = getReservationTypeByMainkey($mainkey); switch($type):{ case 'A': $this->reservationAConfig($mainkey); break; case 'B': $this->reservationBConfig($mainkey); break; ..... } } private function reservationAConfig($mainkey){ //这里进行A配置的预约逻辑操作 } private function reservationBConfig($mainkey){ //这里进行B配置的预约逻辑操作 } private function getReservationTypeByMainkey($mainkey){ //根据预约号获取预约配置的类型 } <?php interface ReservationStrategy { //执行预约配置逻辑操作 public function makeReservation(); } //策略处理类 class ReservationHandler { private $strategy = null; public function __construct(ReservationStrategy $strategy){ $this->$strategy = $strategy; } //封装了策略执行的逻辑,所有执行的预约配置统一调用这个方法 public function makeReservation(){ $this->$strategy->makeReservation(); } } //A配置的具体策略类 class AReservationStrategy implements ReservationStrategy { public function makeReservation(){ //这里执行A配置的逻辑操作 ; } class ReservationFacaory { public static function getReservationInstance($mainkey){ //这里可以根据预约号做具体逻辑生成策略对象 } } //预约控制器代码 class ReservationController { public function makeReservation($mainkey){ //根据工厂对象创建预约策略实例 $reservation = ReservationFacaory::getReservationInstance($mainkey); //传入实例给策略处理类 $handler = new ReservationHandler($reservation); //执行预约策略 $handler->makeReservation(); } } Wooden Speakers https://www.zeshuiplatform.com/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值