策略模式

策略模式

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

在策略模式中,我们创建表示各种策略的对象和一个行为随着策略对象改变而改变的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);

 

posted @ 2021-12-10 20:43  X__cicada  阅读(17)  评论(0编辑  收藏  举报