>  기사  >  백엔드 개발  >  php中的设计模式之策略模式

php中的设计模式之策略模式

WBOY
WBOY원래의
2016-06-23 13:40:37912검색

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

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.