典型的应用场景:当男性用户访问网站上显示男性相关的类目和广告,当女性用户访问网站时显示女性相关的类目和广告,或默认访问时显示指定相关的类目和广告
<?php
interface UserStrategy
{
function showAd();
function showCategory();
}
class FemaleStrategy implements UserStrategy
{
function showAd()
{
echo "female ad\n";
}
function showCategory()
{
echo "female category\n";
}
}
class MaleStrategy implements UserStrategy
{
function showAd()
{
echo "male ad\n";
}
function showCategory()
{
echo "male category\n";
}
}
class OtherStrategy implements UserStrategy
{
function showAd()
{
echo "other ad\n";
}
function showCategory()
{
echo "other category\n";
}
}
class Page
{
private $strategy;
function index()
{
$this->strategy->showAd();
$this->strategy->showCategory();
}
function setStrategy(UserStrategy $strategy)
{
$this->strategy = $strategy;
}
}
$page = new Page;
if($argv[1] == 1) {
$strategy = new FemaleStrategy;
} elseif ($argv[1] == 2) {
$strategy = new OtherStrategy;
} else {
$strategy = new MaleStrategy;
}
$page->setStrategy($strategy);
$page->index();