策略模式是针对一组算法,将每一种算法都封装到具有共同接口的独立的类中,从而是它们可以相互替换。策略模式的最大特点是使得算法可以在不影响客户端的情况下发生变化,从而改变不同的功能。
<?php interface stratege{ public function dooperation($int1,$int2); } class operationadd implements stratege{ public function dooperation($int1,$int2){ return $int1 + $int2; } } class operationsub implements stratege{ public function dooperation($int1,$int2){ return $int1 - $int2; } } class context{ public $stratege; public function __construct(stratege $stra){ $this->stratege = $stra; } public function executestrategy($int1,$int2){ echo $this->stratege->dooperation($int1,$int2)."\n"; } } $add = new operationadd(); $context_add = new context($add); $context_add->executestrategy(5,3); //输出8 $sub = new operationsub(); $context_sub = new context($sub); $context_sub->executestrategy(5,3); //输出2
如对本文有疑问, 点击进行留言回复!!
[ACTF2020 新生赛]Include 1【文件包含】【读取代码】
算法题解 - 牛客编程巅峰赛S1第6场 - 黄金&钻石&王者组
推荐一个程序员必备网站之一:Dev Hints ,非常实用!
网友评论