抽象策略(strategy)角色:定义所有支持的算法的公共接口。通常是以一个接口或抽象来实现。context使用这个接口来调用其concretestrategy定义的算法。
具体策略(concretestrategy)角色:以strategy接口实现某具体算法。
环境(context)角色:持有一个strategy类的引用,用一个concretestrategy对象来配置
核心代码
<?php
interface strategy { // 抽象策略角色,以接口实现
public function algorithminterface(); // 算法接口
}
class concretestrategya implements strategy { // 具体策略角色a
public function algorithminterface() {}
}
class concretestrategyb implements strategy { // 具体策略角色b
public function algorithminterface() {}
}
class concretestrategyc implements strategy { // 具体策略角色c
public function algorithminterface() {}
}
class context { // 环境角色
private $_strategy;
public function __construct(strategy $strategy) {
$this->_strategy = $strategy;
}
public function contextinterface() {
$this->_strategy->algorithminterface();
}
}
// client
$strategya = new concretestrategya();
$context = new context($strategya);
$context->contextinterface();
$strategyb = new concretestrategyb();
$context = new context($strategyb);
$context->contextinterface();
$strategyc = new concretestrategyc();
$context = new context($strategyc);
$context->contextinterface();
其他代码
<?php
/**
* 策略模式(strategy.php)
*
* 定义一系列算法,把它们一个个封装起来,并且使它们可相互替换,使用得算法的变化可独立于使用它的客户
*
*/
// ---以下是一系列算法的封闭----
interface cachetable
{
public function get($key);
public function set($key,$value);
public function del($key);
}
// 不使用缓存
class nocache implements cachetable
{
public function __construct(){
echo "use nocache<br/>";
}
public function get($key)
{
return false;
}
public function set($key,$value)
{
return true;
}
public function del($key)
{
return false;
}
}
// 文件缓存
class filecache implements cachetable
{
public function __construct()
{
echo "use filecache<br/>";
// 文件缓存构造函数
}
public function get($key)
{
// 文件缓存的get方法实现
}
public function set($key,$value)
{
// 文件缓存的set方法实现
}
public function del($key)
{
// 文件缓存的del方法实现
}
}
// ttserver
class ttcache implements cachetable
{
public function __construct()
{
echo "use ttcache<br/>";
// ttserver缓存构造函数
}
public function get($key)
{
// ttserver缓存的get方法实现
}
public function set($key,$value)
{
// ttserver缓存的set方法实现
}
public function del($key)
{
// ttserver缓存的del方法实现
}
}
// -- 以下是使用不用缓存的策略 ------
class model
{
private $_cache;
public function __construct()
{
$this->_cache = new nocache();
}
public function setcache($cache)
{
$this->_cache = $cache;
}
}
class usermodel extends model
{
}
class porductmodel extends model
{
public function __construct()
{
$this->_cache = new ttcache();
}
}
// -- 实例一下 ---
$mdluser = new usermodel();
$mdlproduct = new porductmodel();
$mdlproduct->setcache(new filecache()); // 改变缓存策略
?>
具体的大家可以多关注一下硕编程以前发布的文章
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!