您现在的位置是:网站首页 > 心得笔记

常用设计模式之策略模式

盛悦2025-02-2174人围观
简介本文将记录常用设计模式之策略模式

使用场景

系统需要支持不同的支付形式,现为每个支付网关实现具体的策略。每个策略将封装具体的支付处理逻辑。


1.定义策略接口

// app/Interfaces/IPaymentMethod.php

namespace App\Interfaces;

interface IPaymentMethod
{
    public function pay(float $amount): string;
}

2.实施具体策略

class PayPalStrategy implements IPaymentMethod
{
    public function pay()
    {
    }
}

3.创建上下文类

// app/Strategies/PaymentStrategy.php

命名空间 App\Strategies;

使用App\Interfaces\IPaymentMethod;
使用App\Services\Payment\PayPalStrategy;
使用App\Services\Payment\StripeStrategy;
使用App\Services\Payment\SquareStrategy;
使用Exception ; 

class PaymentStrategy
 { 
    private IPaymentMethod $paymentMethod ; 

    public function getPaymentMethod( string  $gateway ): IPaymentMethod
     { 
        switch ( $gateway ) { 
            case  'paypal' : 
                $this ->paymentMethod = App :: make ( PayPalStrategy :: class ); 
                break ; 
            case  'stripe' : 
                $this ->paymentMethod = App :: make ( StripeStrategy :: class ); 
                break ; 
            case  'square' : 
                $this ->paymentMethod = App :: make ( SquareStrategy :: class ); 
                break ;
            默认:
                抛出 新的 \Exception(“不支持的支付网关 [ $gateway ]”);
       }
       返回 $this ->paymentMethod;
    } 
}