什么是代理模式?(实例说明)

藏色散人
发布: 2023-04-05 20:52:01
转载
4446 人浏览过

代理模式

代理模式的作用和继承以及接口和组合的作用类似,都是为了聚合共用部分,减少公共部分的代码。

不同的是相比起继承,他们的语境不同,继承要表达的含义是 is-a, 而代理要表达的含义更接近于接口, 是 has-a,而且使用代理的话应了一句话"少用继承,多用组合",要表达的意思其实也就是降低耦合度了。

对于组合来说,他比组合更具灵活性,比如我们将代理对象设为private,那么我可以选择只提供一部分的代理功能,例如Printer的某一个或两个方法,又或者在提供Printer的功能的时候加入一些其他的操作,这些都是可以的。

';
    }
}
//这是一个文印处理店,只文印,卖纸,不照相
class TextShop {
    private $printer;
    public function __construct(Printer $printer) {
        $this->printer = $printer;
    }
    //卖纸
    public function sellPaper() {
        echo 'give you some paper 
'; } //将代理对象有的功能交给代理对象处理 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
'; } public function __call($method, $args) { //将代理对象有的功能交给代理对象处理 if(method_exists($this->printer, $method)) { $this->printer->$method($args); } } } $printer = new Printer(); $textShop = new TextShop($printer); $photoShop = new PhotoShop($printer); $textShop->printSth(); $photoShop->printSth();
登录后复制

以上是什么是代理模式?(实例说明)的详细内容。更多信息请关注PHP中文网其他相关文章!

相关标签:
来源:hcoder.net
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!