本文例子来自鹿鼎记的韦小宝
他是一个八面玲珑的人,是一个有策略的人,因此才能在本身不一样的角色转换自如,符合这个设计模式php
对应于策略设计模式
Context(使用者): 韦小宝
Abstract(抽象策略) : 转换角色
Strategy(具体策略) : 遇到了康熙,遇到了天地会,遇到了神龙教,分别是什么角色设计模式
代码实现测试
抽象策略ui
/** * 身份抽象类 * Interface IDEGREE */ interface IDegree { public function role(); }
使用者类设计
/** * 使用角色 * Class Weixiaobao */ class Wxb { public function role(IDegree $degree){ $degree->role(); } }
具体策略类code
/** * 遇到康熙的身份 * Class Kangxi */ include "IDegree.php"; class Kangxi implements IDegree { public function role() { echo '遇到了康熙,变成小桂子'; } }
/** * 遇到了天地会 * Class Tiandihui */ include "IDegree.php"; class Tiandihui implements IDegree { public function role() { echo '遇到了天地会, 我是韦香主'; } }
/** * 碰见了神龙教 * Class Shenlongjiao */ include "IDegree.php"; class Shenlongjiao implements IDegree { public function role() { echo '遇到了神龙教, 我是白龙使'; } }
测试io
/** * 行走江湖都不怕的韦小宝 */ include_once "Wxb.php"; //include_once "Shenlongjiao.php"; include_once "Tiandihui.php"; $wxb = new Wxb(); //皇上派人去攻打神龙教 //$wxb->role(new Shenlongjiao()); $wxb->role(new Tiandihui());