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

PHP设计模式-策略模式

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

PHP设计模式-策略模式

策略模式用途

分离「策略」并使他们之间能互相快速切换。此外,这种模式是一种不错的继承替代方案(替代使用扩展抽象类的方式)。

例子
  • 计算器的设计

代码
  • MathStrategy.php

namespace Strategy;interface MathStrategy{    public function calc(int $num1, int $num2);
}
  • MathAdd.php

namespace Strategy;class MathAdd implements MathStrategy{    public function calc(int $num1, int $num2): int
    {        return $num1 + $num2;
    }
}
  • MathSub.php

namespace Strategy;class MathSub implements MathStrategy{    public function calc(int $num1, int $num2): int
    {        return $num1 - $num2;
    }
}
  • Computer.php

namespace Strategy;class Computer{    public $math_class;    public function __construct(int $type)
    {        if ($type == 1) {            $this->math_class = new MathAdd();
        } elseif ($type == 2) {            $this->math_class = new MathSub();
        }
    }    
    public function getResult(int $num1, int $num2): int
    {        if ($this->math_class === null) echo '对象为空';        return $this->math_class->calc($num1, $num2);
    }
}
  • 实施调用

getResult(1,4);echo '
'; $class2 = new Computer(2);echo $class2->getResult(2, 6);
总结
  • 工厂模式和策略模式的CML图片是相似的,他们区别在于,工厂模式是我们可以直接拿到对象进行操作;策略模式我们拿到的是对象的封装对象。



作者:PHP的艺术编程
链接:https://www.jianshu.com/p/89a64a92c0bb


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

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

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