標籤:策略模式 設計模式 php
<?php/*所謂策略模式是在不同的事件策略模式就是針對相同的行為,在不同的情境中擁有不同的演算法,將這些演算法封裝起來,並且這些演算法是可以互換的,這樣就對客戶隱藏了相應演算法的實現細節,可以很方便的在運行時選擇具體的行為演算法(即策略)。簡單的策略模式: 保安對於學生和老師進考場這個事件,可以分化出不同的策略,學生要查看考試證據,老師允許存取*/interface Strategy{public function handle(); // 執行的策略(function)}/**對學生採取的策略 */class studentStrategy implements Strategy{public function handle(){echo 'check';}}/**對老師採取的策略 */class teacherStrategy implements Strategy{public function handle(){echo 'gogogo';}}// 情形 class TestCheck{private $strategy; //設定策略 public function setStrategy(Strategy $strategy){$this->strategy = $strategy;}// 開始策略public function startStrategy(){$this->strategy->handle(); }}$people = 'teacher';switch($people){case 'student' : $strategy = new studentStrategy () ;break;case 'teacher' : $strategy = new teacherStrategy () ;break;}$safePeople = new TestCheck();$safePeople ->setStrategy($strategy);$safePeople ->startStrategy();
php中的設計模式之--策略模式