Home  >  Article  >  Backend Development  >  PHP Strategy Pattern

PHP Strategy Pattern

不言
不言Original
2018-04-13 17:17:061803browse

The content shared with you in this article is about PHP strategy model, which has certain reference value. Friends in need can refer to it

For example: an e-commerce website system, targeting men and women Users need to jump to different product categories, and all advertising slots display different ads

6 Project Application


6.1 Requirements Description

Implement a shopping mall cashier system. Products can have normal charging, discount charging, rebate charging and other modes (from "Dahua Design Pattern")


6.2 Requirements Analysis

According to the requirements, the charging operation can be designed as an interface algorithm. Normal charging, discount charging, and rebate charging all inherit this interface to implement different strategies. algorithm. Then design an environment class to maintain instances of the policy.


6.3 Design architecture diagram



6.4 Program source code download

http://download.csdn.net/detail/clevercode/8700009

6.5 Program Description


1) strategy.php




[php] view plain copy


    <?php  
    /** 
     * strategy.php 
     * 
     * 策略类:定义了一系列的算法,这些算法都是完成的相同工作,但是实现不同。 
     *   
     * 特别声明:本源代码是根据《大话设计模式》一书中的C#案例改成成PHP代码,和书中的 
     * 代码会有改变和优化。 
     * 
     * Copyright (c) 2015 http://blog.csdn.net/CleverCode 
     * 
     * modification history: 
     * -------------------- 
     * 2015/5/5, by CleverCode, Create 
     * 
     */  
      
    // 定义接口现金策略,每种策略都是具体实现acceptCash,但都是实现收取现金功能  
    interface ICashStrategy{  
        // 收取现金  
        public function acceptCash($money);  
    }  
      
    // 正常收取策略  
    class NormalStrategy implements ICashStrategy{  
      
        /** 
         * 返回正常金额 
         * 
         * @param double $money 金额 
         * @return double 金额 
         */  
        public function acceptCash($money){  
            return $money;  
        }  
    }  
      
    // 打折策略  
    class RebateStrategy implements ICashStrategy{  
        // 打折比例  
        private $_moneyRebate = 1;  
      
        /** 
         * 构造函数 
         * 
         * @param double $rebate 比例 
         * @return void 
         */  
        public function __construct($rebate){  
            $this->_moneyRebate = $rebate;  
        }  
      
        /** 
         * 返回正常金额 
         * 
         * @param double $money 金额 
         * @return double 金额 
         */  
        public function acceptCash($money){  
            return $this->_moneyRebate * $money;  
        }  
    }  
      
    // 返利策略  
    class ReturnStrategy implements ICashStrategy{  
        // 返利条件  
        private $_moneyCondition = null;  
          
        // 返利多少  
        private $_moneyReturn = null;  
      
        /** 
         * 构造函数 
         * 
         * @param double $moneyCondition 返利条件 
         * @return double $moneyReturn 返利多少 
         * @return void 
         */  
        public function __construct($moneyCondition, $moneyReturn){  
            $this->_moneyCondition = $moneyCondition;  
            $this->_moneyReturn = $moneyReturn;  
        }  
      
        /** 
         * 返回正常金额 
         * 
         * @param double $money 金额 
         * @return double 金额 
         */  
        public function acceptCash($money){  
            if (!isset($this->_moneyCondition) || !isset($this->_moneyReturn) || $this->_moneyCondition == 0) {  
                return $money;  
            }  
              
            return $money - floor($money / $this->_moneyCondition) * $this->_moneyReturn;  
        }  
    }


2) strategyPattern.php





##[php]

view plain copy


<?php  
/** 
 * strategyPattern.php 
 * 
 * 设计模式:策略模式 
 *  
 * 模式简介: 
 *     它定义了算法家族,分别封装起来,让它们之间可以互相替换,此模式让算法的变化, 
 * 不会影响到使用算法的客户。 
 *     策略模式是一种定义一些列算法的方法,从概念上来看,所有这些算法完成的都是 
 * 相同的工作,只是实现不同,它可以以相同的方式调用所有的算法,减少了各种算法类 
 * 与使用算法类的耦合。 
 *     本源码中的各种结账方式,其实都是在结账,但是具体的实现确实不同的。策略模式与 
 * 命令模式不同的是,命令模式的算法是相互独立的,每个命令做的工作是不同的。而策略模式 
 * 却是在做通一种工作。           
 *  
 * 特别声明:本源代码是根据《大话设计模式》一书中的C#案例改成成PHP代码,和书中的 
 * 代码会有改变和优化。 
 * 
 * Copyright (c) 2015 http://blog.csdn.net/CleverCode 
 * 
 * modification history: 
 * -------------------- 
 * 2015/5/14, by CleverCode, Create 
 * 
 */  
  
// 加载所有的策略  
include_once (&#39;strategy.php&#39;);  
  
// 创建一个环境类,根据不同的需求调用不同策略  
class CashContext{  
      
    // 策略  
    private $_strategy = null;  
  
    /** 
     * 构造函数 
     * 
     * @param string $type 类型 
     * @return void 
     */  
    public function __construct($type = null){  
        if (!isset($type)) {  
            return;  
        }  
        $this->setCashStrategy($type);  
    }  
  
    /** 
     * 设置策略(简单工厂与策略模式混合使用) 
     * 
     * @param string $type 类型 
     * @return void 
     */  
    public function setCashStrategy($type){  
        $cs = null;  
        switch ($type) {  
              
            // 正常策略  
            case &#39;normal&#39; :  
                $cs = new NormalStrategy();  
                break;  
              
            // 打折策略  
            case &#39;rebate8&#39; :  
                $cs = new RebateStrategy(0.8);  
                break;  
              
            // 返利策略  
            case &#39;return300to100&#39; :  
                $cs = new ReturnStrategy(300, 100);  
                break;  
        }  
        $this->_strategy = $cs;  
    }  
  
    /** 
     * 获取结果 
     * 
     * @param double $money 金额 
     * @return double 
     */  
    public function getResult($money){  
        return $this->_strategy->acceptCash($money);  
    }  
  
    /** 
     * 获取结果 
     * 
     * @param string $type 类型 
     * @param int $num 数量 
     * @param double $price 单价 
     * @return double 
     */  
    public function getResultAll($type, $num, $price){  
        $this->setCashStrategy($type);  
        return $this->getResult($num * $price);  
    }  
}  
  
/* 
 * 客户端类 
 * 让客户端和业务逻辑尽可能的分离,降低客户端和业务逻辑算法的耦合, 
 * 使业务逻辑的算法更具有可移植性 
 */  
class Client{  
  
    public function main(){  
        $total = 0;  
          
        $cashContext = new CashContext();  
          
        // 购买数量  
        $numA = 10;  
        // 单价  
        $priceA = 100;  
        // 策略模式获取结果  
        $totalA = $cashContext->getResultAll(&#39;normal&#39;, $numA, $priceA);  
        $this->display(&#39;A&#39;, &#39;normal&#39;, $numA, $priceA, $totalA);  
          
        // 购买数量  
        $numB = 5;  
        // 单价  
        $priceB = 100;  
        // 打折策略获取结果  
        $totalB = $cashContext->getResultAll(&#39;rebate8&#39;, $numB, $priceB);  
        $this->display(&#39;B&#39;, &#39;rebate8&#39;, $numB, $priceB, $totalB);  
          
        // 购买数量  
        $numC = 10;  
        // 单价  
        $priceC = 100;  
        // 返利策略获取结果  
        $totalC = $cashContext->getResultAll(&#39;return300to100&#39;, $numC, $priceC);  
        $this->display(&#39;C&#39;, &#39;return300to100&#39;, $numC, $priceC, $totalC);  
    }  
  
    /** 
     * 打印 
     * 
     * @param string $name 商品名 
     * @param string $type 类型 
     * @param int $num 数量 
     * @param double $price 单价 
     * @return double 
     */  
    public function display($name, $type, $num, $price, $total){  
        echo date(&#39;Y-m-d H:i:s&#39;) . ",$name,[$type],num:$num,price:$price,total:$total\r\n";  
    }  
}  
  
/** 
 * 程序入口 
 */  
function start(){  
    $client = new Client();  
    $client->main();  
}  
  
start();  
  
?>
  1. Related recommendations:

Example analysis of PHP strategy pattern

PHP Strategy Pattern Definition and Usage Examples

The above is the detailed content of PHP Strategy Pattern. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn