策略模式-应用场景,实现各个平台支付解耦

<?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]);

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值