策略模式
多算法独立于客户端而变化
<?php
/**
* 策略模式
* 知识点:
* 1. 依赖注入
* 2. 多态
*/
// 总的策略接口
Interface Strategy
{
public function totalMethod();
}
// 不同的策略实现类
class StrategyA implements Strategy
{
public function totalMethod()
{
echo "it is stragety_A\n";
}
}
class StrategyB implements Strategy
{
public function totalMethod()
{
echo "it is stragety_B\n";
}
}
class StrategyC implements Strategy
{
public function totalMethod()
{
echo "it is stragety_C\n";
}
}
//上下文环境
class Context
{
private $con_strategy;
public function __construct(Strategy $concrete_strategy)
{
$this->con_strategy = $concrete_strategy;
}
public function handle()
{
$this->con_strategy->totalMethod();
}
}
// 主程序
try {
$context_a = new Context(new StrategyA());
$context_a->handle();
$context_b = new Context(new StrategyB());
$context_b->handle();
$context_c = new Context(new StrategyC());
$context_c->handle();
} catch (Exception $e) {
echo $e->getMessage();
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。