策略模式:定义了算法族,分别封装起来,让它们之间可以互相替换,此模式让算法的变化独立于使用算法的客户。
封装: 把行为用接口封装起来,我们可以把那些经常变化的部分,从当前的类中单独取出来,用接口进行单独的封装。
互相替换:我们封装好了接口,通过指定不同的接口实现类进行算法的变化,
以适应某些特定的上下文环境。
<?php /** * Created by PhpStorm. * User: Administrator * Date: 2017/8/23 * Time: 16:22 */ interface Shoes { public function ShoesList(); } class Man implements Shoes { public function ShoesList() { echo "man list"; } } class Woman implements Shoes { public function ShoesList() { echo "woman list"; } } class UserStrategy { public $strategy; public function __construct(Shoes $shoes) { $this->strategy = $shoes; } public function ShoesList() { $this->strategy->ShoesList(); } } $sex = 1; switch ($sex) { case 1: (new UserStrategy(new Man()))->ShoesList(); break; case 2: (new UserStrategy(new Woman()))->ShoesList(); break; }
结果:
D:\myapache\www\demo\guancazhe>php Strategy.php
man list
使用策略模式,使得我们的程序可以根据不同的参数,调取不同的结果。