PHP設計模式 - 策略模式

策略模式主要爲了讓客戶類可以更好地使用某些算法而不須要知道其具體的實現。php

<?php
interface Strategy { // 抽象策略角色,以接口實現
    public function do_method(); // 算法接口
}

class ConcreteStrategyA implements Strategy { // 具體策略角色A 
    public function do_method() {
        echo 'do method A';
    }
}

class ConcreteStrategyB implements Strategy { // 具體策略角色B 
    public function do_method() {
        echo 'do method B';
    }
}

class ConcreteStrategyC implements Strategy { // 具體策略角色C
    public function do_method() {
        echo 'do method C';
    }
}


class Question{ // 環境角色
    private $_strategy;

    public function __construct(Strategy $strategy) {
        $this->_strategy = $strategy;
    } 
    public function handle_question() {
        $this->_strategy->do_method();
    }
}

// client
$strategyA = new ConcreteStrategyA();
$question = new Question($strategyA);
$question->handle_question();//輸出do method A

$strategyB = new ConcreteStrategyB();
$question = new Question($strategyB);
$question->handle_question();//輸出do method B

$strategyC = new ConcreteStrategyC();
$question = new Question($strategyC);
$question->handle_question();//輸出do method C
相關文章
相關標籤/搜索