Home > Backend Development > PHP Tutorial > php中的设计模式之策略模式

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

WBOY
Release: 2016-06-23 13:40:37
Original
960 people have browsed it

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

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template