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