4个PHP文件
index.php 主入口
app\UserStrategy.php 接口文件
app\FemaleUserStrategy.php 策略文件
app\MaleUserStrategy.php 策略文件
require 'App\UserStrategy.php';
require 'App\FemaleUserStrategy.php';
require 'App\MaleUserStrategy.php';
use App\UserStrategy;
use App\FemaleUserStrategy;
use App\MaleUserStrategy;
class Page{
protected $strategy;
function index(){
$this->strategy->showAd();
echo "<br/>";
$this->strategy->showCategory();
}
function setStrategy(UserStrategy $strategy){
$this->strategy=$strategy;
}
}
$page=new Page;
if(isset($_GET['female'])){
$strategy=new FemaleUserStrategy();
}else{
$strategy=new MaleUserStrategy();
}
$page->setStrategy($strategy);
$page->index();
namespace App;
interface UserStrategy {
function showAd();
function showCategory();
}
namespace App;
//策略模式-男
class MaleUserStrategy implements UserStrategy {
function showAd() {
echo "IPhone6";
}
function showCategory() {
echo "电子产品";
}
}
namespace App;
//策略模式-女
class FemaleUserStrategy implements UserStrategy {
function showAd() {
echo "2014新款女装";
}
function showCategory() {
echo "女装";
}
}
网友评论