策略模式

策略模式

  • 多算法獨立於客戶端而變化php

<?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();
}
相關文章
相關標籤/搜索
本站公眾號
   歡迎關注本站公眾號,獲取更多信息