策略模式-應用場景,實現各個平臺支付解耦

<?php

//支付接口
interface PaymentInterface {
    /**支付動作
     * @param array $param
     * @return boolean
     */
    public function pay($param = array());
}
//支付抽象類
abstract class PaymentAbstract
{
    public static function usable(){
        return false;
    }

}
//微信支付
class WxPayment extends PaymentAbstract implements PaymentInterface {
    public static function usable($param = array())
    {
        //如果使用微信支付
       return $param == 'wx';
    }

    public function pay($param = array())
    {
        // TODO: Implement pay() method.
    }
}
//支付寶支付
class AliPayment extends PaymentAbstract implements PaymentInterface {
    public static function usable($param = array())
    {
        //如果使用支付寶支付
        return $param == 'alipay';
    }

    public function pay($param = array())
    {
        // TODO: Implement pay() method.
    }
}

//支付類工廠
class PaymentFactory
{
    public static function getInterface($payType)
    {
        //寫到配置文件中
        $config = [
            'payList' => [
                WxPayment::class,
                AliPayment::class
            ],
        ];
        foreach($config['payList'] as $class)
        {
            try{
                //調用各個靜態方法
                $isUsable = $class::usable($payType);
                if($isUsable === true)
                {
                    //如果滿足這個支付類的調用條件
                    $payMent = new $class();
                    //支付類必須實現支付接口
                    if (!$payMent instanceof PaymentInterface)
                    {
                        throw new Exception($class.' is not instance of Payment');
                    }
                    return $payMent;
                }
            }catch (Exception $e)
            {
                echo $e->getMessage();
                die;
            }

        }
    }
}

//支付類
class Payment{
    protected $payment;
    public function __construct($type)
    {
        $this->payment = PaymentFactory::getInterface($type);
    }

    public function pay($data = [])
    {
        return $this->payment->pay($data);
    }
}


//支付
(new Payment('ali'))->pay(['price'=>100.00]);

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章