天天看点

初识PHP设计模式--策略模式

  策略模式(Strategy)是一种行为型模式。

 百度定义:策略模式是指对一系列的算法定义,并将每一个算法封装起来,而且使它们还可以相互替换。策略模式让算法独立于使用它的客户而独立变化。

 理解起来并不是很难,策略模式是一种算法的灵活实现,通俗点讲,就是一个功能有多条途径去实现,

 拥有一个抽象策略类,具体策略的灵活性就体现在,出现新的算法策略时只需要添加一个具体算法策略就行。

 举个简单的例子,我们都吃过外卖,外卖的店家会有很多营销策略去促使消费,比如满30减10,满60减30。

 代码如下:

<?php

header("Content-Type:text/html;charset=utf-8");

require_once "Strategy.php";

// 创建策略对象
$obj = new Strategy();

// 满足60元
$obj->GetPrice("RMB60");
$obj->ShowPrice();

// 满足30元
$obj->GetPrice("RMB30");
$obj->ShowPrice();
           
<?php
// 策略接口
interface IStrategy 
{
    /**  
     * 显示价格 子类必须实现  
     * @access public     
     */
    function ShowPrice();
}
//满60
Class RMB60 implements IStrategy
{
    /**  
     * 显示价格  
     * @access public     
     */
    function ShowPrice(){
       echo "满60减30,实际付款30元<br/>";
    }
}
// 满30
Class RMB30 implements IStrategy
{
    /**  
     * 显示价格  
     * @access public     
     */
	function ShowPrice(){
       echo "满20减10,实际付款20元<br/>";
	}
}
//策略对象
Class Strategy {
    /**  
     * 获取价格值  
     * @var string  
     */
	private $money;

    /**  
     * 获取价格,创建对象  
     * @access public   
     * @param  string $money  
     */
	function GetPrice($money)
	{
        // PHP一种创建对象的方法
        $class = new ReflectionClass($money);
        $this->item = $class->newInstance(); 
	}

    /**  
     * 显示价格  
     * @access public     
     */
	function ShowPrice(){
        $this->item->ShowPrice();
	}
}
           

结果如下:

满60减30,实际付款30元

满20减10,实际付款20元

继续阅读