码迷,mamicode.com
首页 > 其他好文 > 详细

代理模式

时间:2015-11-26 18:44:46      阅读:87      评论:0      收藏:0      [点我收藏+]

标签:

<html>
<body>
<?php
//代理对象,一台打印机
class Printer
{
    public function printSth($args)
    {
        echo ‘I can print‘.$args[0].‘<br>‘;
    }
    // some more function below
    // ...
}

//这是一个文印处理店,只文印,卖纸,不照相
class TextShop
{
    private $printer;
    public function __construct(Printer $printer)
    {
        $this->printer = $printer;
    }
    //卖纸
    public function sellPaper()
    {
        echo ‘give you some paper <br>‘;
    }
    //将代理对象有的功能交给代理对象处理
    public function __call($method, $args)
    {
        if(method_exists($this->printer, $method))
        {
            $this->printer->$method($args);
        }
    }
}

//这是一个照相店,只文印,拍照,不卖纸
class PhotoShop
{
    private $printer;

    public function __construct(Printer $printer)
    {
        $this->printer = $printer;
    }

    //照相
    public function takePhotos()
    {
        echo ‘take photos for you <br>‘;
    }

    //将代理对象有的功能交给代理对象处理
    //当本对象没有$textShop->printSth("_t")要的printSht方法时,__call函数被调用
    //$method是$textShop->printSth("_t")中将要使用的方法printSth
    //$args是$textShop->printSth("_t")里头的参数_t
    public function __call($method, $args)
    {
        if(method_exists($this->printer, $method))//检查$this->printer中有没有$method方法
        {
            $this->printer->$method($args);//这里的printer是代理了new Printer的功能
        }
    }
}

$printer = new Printer();
$textShop = new TextShop($printer);
$photoShop = new PhotoShop($printer);

$textShop->printSth("_t");
$photoShop->printSth("_p");
?>
</body>
</html>
各个店都要打印,但没有打印功能,就代理了一台公共的外部打印机
当有需要打印时,__call函数就其作用了

 

代理模式

标签:

原文地址:http://www.cnblogs.com/jiufen/p/4998475.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!