设计模式之代理模式

Posted: 2015-10-16  By  vilay  |  Views(652)

代理模式为其它对象提供一种代理以控制这个对象的访问。

场景实例:追求者(真实实体)追MM,但是害羞不敢追,叫朋友(代理)代为送礼物

首先定义个共有接口:

interface GiveGift {

function giveFlowers();
function giveFoods();
}

真实实体实现接口:

class Pursuit implements GiveGift {

protected $mm = null;

public function __construct(Girl $mm)
{
    $this->mm = $mm;
}

public function giveFlowers()
{
    echo $this->mm->name.',我送你花'.'<br>';
}

public function giveFoods()
{
    echo $this->mm->name.',我送你吃的'.'<br>';
}
}

代理实现相同的接口用来可以代替实体,但保存一个引用让代理可以访问实体:

class Proxy implements GiveGift {

protected $gg = null;

public function __construct(Girl $mm)
{
    $this->gg = new Pursuit($mm);
}

public function giveFlowers()
{
    $this->gg->giveFlowers();
}

public function giveFoods()
{
    $this->gg->giveFoods();
}
}

MM类:

class Girl {
public $name = '';
public function setName($name) {
    $this->name = $name;
}
}

客户端代码:

$mm = new Girl();
$mm->setName('hellokity');

$proxy = new Proxy($mm);
$proxy->giveFoods();
$proxy->giveFlowers();

结果:

hellokity,我送你吃的
hellokity,我送你花