Home  >  Article  >  Backend Development  >  What is proxy mode? (Example description)

What is proxy mode? (Example description)

藏色散人
藏色散人forward
2019-04-16 10:52:244540browse

Proxy mode

The role of proxy mode is similar to that of inheritance, interfaces and combinations, both to aggregate common parts and reduce the code of common parts.

The difference is that compared to inheritance, their contexts are different. The meaning that inheritance wants to express is is-a, while the meaning that proxy wants to express is closer to the interface, which is has-a, and if you use a proxy In response to the sentence "use inheritance less and use combination more", the meaning is actually to reduce the degree of coupling.

For combination, it is more flexible than combination. For example, if we set the proxy object to private, then I can choose to provide only part of the proxy function, such as one or two methods of Printer, and Or you can add some other operations when providing Printer functions. These are all possible.

<?php
//代理对象,一台打印机
class Printer { 
    public function printSth() {
        echo &#39;我可以打印<br>&#39;;
    }
}
//这是一个文印处理店,只文印,卖纸,不照相
class TextShop {
    private $printer;
    public function __construct(Printer $printer) {
        $this->printer = $printer;
    }
    //卖纸
    public function sellPaper() {
        echo &#39;give you some paper <br>&#39;;
    }
    //将代理对象有的功能交给代理对象处理
    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 &#39;take photos for you <br>&#39;;
    }
    
    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();

The above is the detailed content of What is proxy mode? (Example description). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:hcoder.net. If there is any infringement, please contact admin@php.cn delete