zoukankan      html  css  js  c++  java
  • 策略模式

    策略模式

    在策略模式中,一个类的行为或其算法可以在运行时更改.这种类型的设计模式属于行为型模式

    在策略模式中,我们创建表示各种策略的对象和一个行为随着策略对象改变而改变的context对象,策略对象改变context对象的执行算法

    代码

    1 创建一个接口

    <?php
    interface Strategy
    {
        public  function doOperation($a,$b);
    }
    

    2 创建实现接口的实体类

    <?php
    
    class OperationAdd implements Strategy
    {
    
    
        public function doOperation($a, $b)
        {
            return $a + $b;
        }
    }
    <?php
    
    class  OperationMultiply implements Strategy
    {
    
        public function doOperation($a, $b)
        {
    
            return $a * $b;
    
        }
    }

    3 创建context类

    <?php
     
    
    class  Context
    {
    
        private $_strategy;
    
        public function __construct(Strategy $strategy)
        {
            $this->_strategy = $strategy;
        }
    
        public function executeStrategy($a, $b)
        {
    
            return $this->_strategy->doOperation($a, $b);
        }
    }
     

    4 执行

     $context = new Context(new OperationAdd());
     $context->executeStrategy(1,2);
    $context = new Context(new OperationMultiply());
    $context->executeStrategy(1,2);
  • 相关阅读:
    单例设计模式
    HashMap 排序
    代理、动态代理
    冒泡排序 、二分查找、快速排序
    Azure powershell 订阅登录管理
    cmdbuild -2.4.3 在Centos7部署
    Zabbix3.0 安装部署
    nginx 一键安装
    通过菜单一键安装mysql
    Rsync同步工具
  • 原文地址:https://www.cnblogs.com/aln0825/p/15673796.html
Copyright © 2011-2022 走看看