需求:對于不同的用戶展示不同的內容
* * * * *
**定義接口**
~~~
interface UserStrategy{
function showAd();//展示廣告
function showCategory();//展示分類
}
~~~
* * * * *
**普通用戶展示的內容**
~~~
class CommonUser implements UserStrategy{
public function showAd()
{
// TODO: Implement showAd() method.
//展示普通用戶廣告
}
public function showCategory()
{
// TODO: Implement showCategory() method.
//展示普通用戶商品分類
}
}
~~~
* * * * *
**vip用戶展示的內容**
~~~
class VipUser implements UserStrategy{
public function showAd()
{
// TODO: Implement showAd() method.
//展示會員廣告
}
public function showCategory()
{
// TODO: Implement showCategory() method.
//展示會員商品分類
}
}
~~~
* * * * *
**設置用戶對象,展示用戶頁面**
~~~
class UserPage{
protected $user_object;//用戶對象,vip用戶或普通用戶
/*
* 設置用戶對象
* */
function strategy(UserStrategy $strategy){
$this->user_object = $strategy;
}
function index(){
$ad = $this->user_object->showAd();//獲取廣告
$category = $this->user_object->showAd();//獲取商品分類
}
}
~~~
* * * * *
**根據不同用戶,展示不同界面**
~~~
if($is_vip == true){
$strategy = new \VipUser();
}else{
$strategy = new \CommonUser();
}
$user_page = new UserPage();
$user_page->strategy($strategy)->index();
~~~