栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > PHP

PHP设计模式-策略模式Strategy

PHP 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

PHP设计模式-策略模式Strategy

1.策略模式概念
策略模式针对一组算法,将每一个算法封装到具有共同接口的独立的类中,此模式让算法的变化独立于使用算法的客户。从而让程序结构更灵活,具有更好的扩展性和维护性
2.策略模式结构图

3.策略模式角色说明
    抽象策略(Strategy)角色:定义所有支持的算法的公共接口。通常是以一个接口或抽象来实现。Context使用这个接口来调用其ConcreteStrategy定义的算法。
    具体策略(ConcreteStrategy)角色:以Strategy接口实现某具体算法
    环境(Context)角色:持有一个Strategy类的引用,用一个ConcreteStrategy对象来配置
4.策略模式实例 

interface Strategy {  

 

  public function algorithmInterface();

}  

class ConcreteStrategyA implements Strategy {

   

  public function algorithmInterface() {

    echo 'algorithmInterface A
';

  }

}  

class ConcreteStrategyB implements Strategy {

   

  public function algorithmInterface() {

    echo 'algorithmInterface B
';

  }

}  

class ConcreteStrategyC implements Strategy {

   

  public function algorithmInterface() {

    echo 'algorithmInterface C
';

  }

}

   

class Context {

 

  private $_strategy;

   

  public function __construct(Strategy $strategy) {

    $this->_strategy = $strategy;

  }

   

  public function contextInterface() {

    $this->_strategy->algorithmInterface();

  }

   

}  

class Client {

   

 

  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();

?>



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/229116.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号