策略模式

  • 多算法独立于客户端而变化

<?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();
}

蛇叔编程心法
16 声望1 粉丝

爱生活,爱学习,爱工作,足够拼命,足够努力。


« 上一篇
简单工厂模式
下一篇 »
装饰器模式