代办形式的作用和继续以及接口和组合的作用相似,都是为了聚合共用部份,削减大众部份的代码。
差别的是相比起继续,他们的语境差别,继续要表达的寄义是 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();
以上就是什么是代办形式?(实例申明)的细致内容,更多请关注ki4网别的相干文章!