代理模式:代理模式的作用和繼承以及接口和組合的作用類似,都是為了聚合共用部分,減少公共部分的代碼。
不同的是相比起繼承,他們的語境不同,繼承要表達的含義是 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();
新聞熱點
疑難解答