将一组特定的行为和算法封装成类,以适应某些特定的上下文环境。
使用场景: 个人理解,策略模式是依赖注入,控制反转的基础
例如:一个电商网站系统,针对男性女性用户要各自跳转到不同的商品类目,并且所有广告位展示不同的广告
MaleUserStrategy.php
<?php
namespace IMooc;
class MaleUserStrategy implements UserStrategy {
function showAd()
{
echo "IPhone6";
}
function showCategory()
{
echo "电子产品";
}
}
FemaleUserStrategy.php
<?php
namespace IMooc;
class FemaleUserStrategy implements UserStrategy {
function showAd()
{
echo "2014新款女装";
}
function showCategory()
{
echo "女装";
}
}
UserStrategy.php
<?php
namespace IMooc;
interface UserStrategy {
function showAd();
function showCategory();
}
<?php
interface FlyBehavior{
public function fly();
}
class FlyWithWings implements FlyBehavior{
public function fly(){
echo "Fly With Wings \n";
}
}
class FlyWithNo implements FlyBehavior{
public function fly(){
echo "Fly With No Wings \n";
}
}
class Duck{
private $_flyBehavior;
public function performFly(){
$this->_flyBehavior->fly();
}
public function setFlyBehavior(FlyBehavior $behavior){
$this->_flyBehavior = $behavior;
}
}
class RubberDuck extends Duck{
}
// Test Case
$duck = new RubberDuck();
/* 想让鸭子用翅膀飞行 */
$duck->setFlyBehavior(new FlyWithWings());
$duck->performFly();
/* 想让鸭子不用翅膀飞行 */
$duck->setFlyBehavior(new FlyWithNo());
$duck->performFly();
评论 (0)