PHP设计模式-适配器模式
2021/11/17 11:10:44
本文主要是介绍PHP设计模式-适配器模式,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
一、概述
将一个类的接口转换成兼容接口,使原本由于接口不兼容不能一起工作的类可以一起工作,通俗的讲:将已经存在的的类创建一个“中间类”,用户直接调用该中间类
二、核心
- 属于结构型设计模式
- 将不同规格的设备通过统一规格的适配器对接到你的系统中
- 常用于和第三方库结合使用,因为第三方库的代码不允许修改
三、结构图
四、代码示例
<?php /* * 适配器模式 */ /* * 类Cat和Dog已经存在,我们需要设计适配器类继承主类,对外开放统一调用 */ class Cat { public function eatfish() { return "Cat eat fish!"; } } class Dog { public function eatBone() { return "Dog eat Bone!"; } } /* * 设计适配器类 */ interface Adapter { public function Eat(); } class CatAdapter extends Cat implements Adapter { public function Eat() { return $this->eatfish(); } } class DogAdapter extends Dog implements Adapter { public function Eat() { return $this->eatBone(); } } /* * 主业务 */ class Animal { private $adapter; public function __construct($obj) { $this->adapter = $obj; } public function Eat() { return $this->adapter->Eat(); } } //小猫吃东西 $catObj = new CatAdapter(); $animal = new Animal($catObj); $animal->Eat(); //小狗吃东西 $dogObj = new DogAdapter(); $animal = new Animal($dogObj); $animal->Eat();
五、总结
- 其中CatClass和DogClass为原始类,在不修改的情况下,用户想要灵活调用类中的eatfish(eatBone)方法,可以为该类加上适配器
CatAdpterClass和DogAdpterClass
这篇关于PHP设计模式-适配器模式的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-03-29env: php: no such file or directory
- 2024-03-01php foreach break
- 2024-02-26Exception参数 php-icode9专业技术文章分享
- 2023-12-30PHP文件批量上传-icode9专业技术文章分享
- 2023-12-30thinkphp6 withJoin-icode9专业技术文章分享
- 2023-12-27MagicArray:像php一样,让Go业务代码不再卷!
- 2023-11-18centos7编译安装PHP教程。
- 2023-11-18centos7编译安装phpMyAdmin教程。
- 2023-10-13唱衰这么多年,PHP 仍然还是你大爷!
- 2023-07-25PHP8,性能更好,语法更好,类型安全更完善