政策模式(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元