設計模式(二)之策略模式

1.策略模式:是對象的行爲模式,用意是對一組算法的封裝。動態的選擇須要的算法並使用。php

實現步驟:算法

1.定義抽象類(定義全部子類必需要實現的共同抽象方法this

2.定義具體策略類(具體實現父類的共同方法)spa

3.定義環境角色類(私有化申明抽象角色變量,重載構造方法,執行抽象方法)code

目的;根據不一樣渠道實現不通的渠道接口;router

好比下面的實現支付渠道相關接口;對象

Channel.phpblog

<?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();
?>
相關文章
相關標籤/搜索