策略模式:
將一組特定的行為和演算法封裝成類,以適應某些特定的上下文環境;
實際應用舉例,假如一個電商網站系統,針對男性女性用戶要各自跳到不同的商品類目,且所有廣告位展示不同的廣告。
UserStrategy.php
<?<span>php namespace Baobab; </span><span>interface</span><span> UserStrategy{ </span><span>function</span><span> showAd(); </span><span>function</span><span> showCategory(); } </span>?>
FemaleUserStrategy.php
<?<span>php namespace Baobab; </span><span>class</span> FemaleUserStrategy <span>implements</span><span> UserStrategy{ </span><span>function</span><span> showAd(){ </span><span>echo</span> '2016新款女装'<span>; } </span><span>function</span><span> showCategory(){ </span><span>echo</span> '女装'<span>; } } </span>?>
MaleUserStrategy.php
<?<span>php namespace Baobab; </span><span>class</span> MaleUserStrategy <span>implements</span><span> UserStrategy{ </span><span>function</span><span> showAd(){ </span><span>echo</span> 'Iphone6s plus'<span>; } </span><span>function</span><span> showCategory(){ </span><span>echo</span> '电子产品'<span>; } } </span>?>
MaleUserStrategy.
<span><span>namespace Baobab;</span><br>class</span><span> Page{ </span><span>protected</span><span>$strategy</span><span>; </span><span>function</span><span> Index(){ </span><span>$this</span>->strategy-><span>showAd(); </span><span>echo</span> '<br/>'<span>; </span><span>$this</span>->strategy-><span>showCategory(); } </span><span>function</span> setStrategy(\Baobab\UserStrategy <span>$strategy</span><span>){ </span><span>$this</span>->strategy = <span>$strategy</span><span>; } } </span>
以上就介紹了php設計模式 策略模式,包含了面向的內容,希望對PHP教學有興趣的朋友有幫助。