案例解析代理模式是什么?这个问题可能是我们日常学习或工作经常见到的。希望通过这个问题能让你收获颇深。下面是小编给大家带来的参考内容,让我们一起来看看吧!
代理模式
代理模式的作用和继承以及接口和组合的作用类似,都是为了聚合共用部分,减少公共部分的代码。
不同的是相比起继承,他们的语境不同,继承要表达的含义是 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->printer->$method($args);
}
}
}
$printer = new Printer();
$textShop = new TextShop($printer);
$photoShop = new PhotoShop($printer);
$textShop->printSth();
$photoShop->printSth();
感谢各位的阅读!看完上述内容,你们对案例解析代理模式是什么大概了解了吗?希望文章内容对大家有所帮助。如果想了解更多相关文章内容,欢迎关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。