zoukankan      html  css  js  c++  java
  • 设计模式(二)之策略模式

    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();
    ?>
  • 相关阅读:
    c++字符串
    Ubuntu系统的安装与使用 深度音乐播放器
    Ubuntu14.04安装wineqq国际版
    pythonchallenge 解谜 Level 0
    Ubuntu 14.04 安装pdf阅读器
    Ubuntu换源
    pythonchallenge 解谜
    java实现图像灰度化
    c语言完成宽带拨号
    应用程序权限设计
  • 原文地址:https://www.cnblogs.com/wanglijun/p/10927422.html
Copyright © 2011-2022 走看看