以投放广告为例:
namespace IMooc; interface UserStrategy{ function showAd(); function showCategory(); }
namespace IMooc; use IMooc; class FamaleUserStrategy implements UserStrategy{ function showAd(){ echo "2016新款女装"; } function showCategory(){ echo "女装"; } }
namespace IMooc; class MaleUserStrategy implements UserStrategy{ function showAd(){ echo "surface pro5"; } function showCategory(){ echo "电子产品"; } }
class Page{ protected $strategy; function index(){ $this->strategy->showAd(); echo "\n"; $this->strategy->showCategory(); } function setStrategy(\IMooc\UserStrategy $strategy){ $this->strategy = $strategy; } } $page = new Page; if(isset($_GET['famale'])){ $strategy = new IMooc\FamaleUserStrategy(); }else{ $strategy = new IMooc\MaleUserStrategy(); } $page->setStrategy($strategy); $page->index();
实现了解耦合与控制反转。