• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

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

php 搞代码 4年前 (2022-01-21) 17次浏览 已收录 0个评论

代理模式

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

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

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

<?php//代理对象,一台打印机class Printer {     public function printSth() {        echo '我可以打印<br>';    }}//这是一个文印处理店,只文印,卖纸,不照相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>';    }        public function __call($method, $args) {    //将代理对象有的功能交给代理对象处理        if(method_exists($this->printer, $method)) {            $this-&g<strong style="color:transparent">9来源gaodai#ma#com搞@代~码$网</strong>搞gaodaima代码t;printer->$method($args);        }    }}$printer = new Printer();$textShop = new TextShop($printer);$photoShop = new PhotoShop($printer);$textShop->printSth();$photoShop->printSth();

以上就是什么是代理模式?(实例说明)的详细内容,更多请关注搞代码gaodaima其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:什么是代理模式?(实例说明)
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址