What is proxy mode? (Example description)

藏色散人
Release: 2023-04-05 20:52:01
forward
4408 people have browsed it

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.

';
    }
}
//这是一个文印处理店,只文印,卖纸,不照相
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();
Copy after login

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!

Related labels:
source:hcoder.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact [email protected]
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!