PHP设计模式-策略模式Strategy

发布时间:2020-08-28 10:14:16 作者:侯施群
来源:网络 阅读:946

1.策略模式概念
策略模式针对一组算法,将每一个算法封装到具有共同接口的独立的类中,此模式让算法的变化独立于使用算法的客户。从而让程序结构更灵活,具有更好的扩展性和维护性
2.策略模式结构图
PHP设计模式-策略模式Strategy
3.策略模式角色说明
    抽象策略(Strategy)角色:定义所有支持的算法的公共接口。通常是以一个接口或抽象来实现。Context使用这个接口来调用其ConcreteStrategy定义的算法。
    具体策略(ConcreteStrategy)角色:以Strategy接口实现某具体算法
    环境(Context)角色:持有一个Strategy类的引用,用一个ConcreteStrategy对象来配置
4.策略模式实例 

<?php
/**
 * 抽象策略角色,以接口实现
 */
interface Strategy {  
  /**
   * 算法接口
   */
  public function algorithmInterface();
}  
/**
 * 具体策略角色A
 */
class ConcreteStrategyA implements Strategy {
  
  public function algorithmInterface() {
    echo 'algorithmInterface A<br />';
  }
}  
/**
 * 具体策略角色B
 */
class ConcreteStrategyB implements Strategy {
  
  public function algorithmInterface() {
    echo 'algorithmInterface B<br />';
  }
}  
/**
 * 具体策略角色C
 */
class ConcreteStrategyC implements Strategy {
  
  public function algorithmInterface() {
    echo 'algorithmInterface C<br />';
  }
}
  
/**
 * 环境角色
 */
class Context {
  /* 引用的策略 */
  private $_strategy;
  
  public function __construct(Strategy $strategy) {
    $this->_strategy = $strategy;
  }
  
  public function contextInterface() {
    $this->_strategy->algorithmInterface();
  }
  
}  
/**
 * 客户端
 */
class Client {
  
  /**
   * Main program.
   */
  public static function main() {
    $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();
  }
  
}  
Client::main();
?>

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

上一篇:css3实现元素环绕中心点布局的方法

下一篇:JavaScript中Object.freeze()的使用方法

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》