设计模式(二)之策略模式

1.策略模式:是对象的行为模式,用意是对一组算法的封装。动态的选择需要的算法并使用。

实现步骤:

1.定义抽象类(定义所有子类必须要实现的共同抽象方法

2.定义具体策略类(具体实现父类的共同方法)

3.定义环境角色类(私有化申明抽象角色变量,重载构造方法,执行抽象方法)

目的;根据不同渠道实现不通的渠道接口;

比如下面的实现支付渠道相关接口;

Channel.php

<?php
/*策略模式:
意图:定义一系列的算法,把它们一个个封装起来, 并且使它们可相互替换。
*/
//渠道类抽象类
abstract class Channel
{
    abstract function getChannel(); //获取渠道状态及其他属性
    abstract function getChannelFee(); //获取渠道费率
    abstract function getChannelConfig();//获取渠道交易秘钥等信息
}

//子渠道cmbc类实现
class cmbc extends Channel
{
    protected $name;
    protected $config;
    protected $fee;
    function __construct($name){
        $this->name = $name;
    }
    function getChannel(){
        return $this->name;
    }
    function getChannelFee(){
        return $this->fee;
    }
    function getChannelConfig(){
        return $this->config;
    }
}
//子渠道 alipay 
class alipay extends Channel
{
    protected $name;
    protected $config;
    protected $fee;
    function __construct($name){
        $this->name = $name;
    }
    function getChannel(){
        return $this->name;
    }
    function getChannelFee(){
        return $this->fee;
    }
    function getChannelConfig(){
        return $this->config;
    }
}
//总路由
class RouterChannel
{
    public $chn;
    public function __construct($channel){
        $this->chn = $channel;
    }
}
$router = new RouterChannel(new cmbc('民生'));
echo $router->chn->getChannel();
$router = new RouterChannel(new alipay('支付宝'));
echo $router->chn->getChannel();
?>
原文地址:https://www.cnblogs.com/wanglijun/p/10927422.html