适配器模式
现在有这样一个场景,某公司有一群动物,各种动物会吃饭,说话,普通实现方式就是写一个父类,其子类去继承父类实现该方法;
<?php abstract class subject { abstract function talk(); abstract function eat(); } class cat extends subject { public function talk() { echo 'I can talk'; } public function eat() { echo 'I can eat'; } }
现在其他动物要进来,不过他们调用的方式是doTalk和doEat两种方法,如果实现的话就是直接在增加两个方法
<?php abstract class subject { abstract function talk(); abstract function eat(); abstract function doTalk(); abstract function doEat(); } class cat extends subject { public function talk() { echo 'I can talk'; } public function eat() { echo 'I can eat'; } public function doTalk() { $this->talk(); } public function doEat() { $this->eat(); } }
可是以后陆续增加其他动物,程序员的工作量就特别大,如果要修改一些方法,那程序员会发疯的基本;有其他方法解决吗?当然有了,就是今天的主角,适配器模式。
<?php abstract class subject { abstract function talk(); abstract function eat(); abstract function doTalk(); abstract function doEat(); } class cat extends subject { public function talk() { echo 'I can talk'; } public function eat() { echo 'I can eat'; } public function doTalk() { $this->talk(); } public function doEat() { $this->eat(); } } interface dog { public function doTalk(); public function doEat(); } class dogAdapter implements dog { private $_adaptee; public function __construct(subject $adaptee) { $this->_adaptee = $adaptee; } public function doTalk() { $this->_adaptee->talk(); } public function doEat() { $this->_adaptee->eat(); } }
这样写就降低了代码的耦合度,实现了程序设计的开闭原则:对扩展开发,对修改关闭。