学习php设计模式 php实现适配器模式_php技巧
一、意图 将一个类的接口转换成客户希望的另外一个接口。Adapter模式使得原来由于接口不兼容而不能一起工作的那此类可以一起工作 二、适配器模式结构图 三、适配器模式中主要角色 <?php/** * 目标角色 */interface Target { /** * 源类也有的方法1 */ public function sampleMethod1(); /** * 源类没有的方法2 */ public function sampleMethod2();} /** * 源角色 */class Adaptee { /** * 源类含有的方法 */ public function sampleMethod1() { echo 'Adaptee sampleMethod1 <br />'; }} /** * 类适配器角色 */class Adapter extends Adaptee implements Target { /** * 源类中没有sampleMethod2方法,在此补充 */ public function sampleMethod2() { echo 'Adapter sampleMethod2 <br />'; } } class Client { /** * Main program. */ public static function main() { $adapter = new Adapter(); $adapter->sampleMethod1(); $adapter->sampleMethod2(); } } Client::main();?> 七、对象适配器模式PHP示例 <?php/** * 目标角色 */interface Target { /** * 源类也有的方法1 */ public function sampleMethod1(); /** * 源类没有的方法2 */ public function sampleMethod2();} /** * 源角色 */class Adaptee { /** * 源类含有的方法 */ public function sampleMethod1() { echo 'Adaptee sampleMethod1 <br />'; }} /** * 类适配器角色 */class Adapter implements Target { private $_adaptee; public function __construct(Adaptee $adaptee) { $this->_adaptee = $adaptee; } /** * 委派调用Adaptee的sampleMethod1方法 */ public function sampleMethod1() { $this->_adaptee->sampleMethod1(); } /** * 源类中没有sampleMethod2方法,在此补充 */ public function sampleMethod2() { echo 'Adapter sampleMethod2 <br />'; } } class Client { /** * Main program. */ public static function main() { $adaptee = new Adaptee(); $adapter = new Adapter($adaptee); $adapter->sampleMethod1(); $adapter->sampleMethod2(); } } Client::main();?> 以上就是使用php实现适配器模式的代码,还有一些关于适配器模式的概念区分,希望对大家的学习有所帮助。 |