PHP设计模式之适配器模式
封面图
•
2025-11-09
•
PHP
286
0
0
0
在 PHP 中,**适配器模式(Adapter Pattern)** 是一种常用的**结构型设计模式**,用于将一个类的接口转换成客户期望的另一个接口。它常用于**兼容不同接口或系统之间的交互**,特别是在你不能修改现有类的情况下。 --- ## 🧩 一、什么是适配器模式? 适配器模式通过包装一个对象,使其能够与另一个接口兼容。简单来说: - **目标接口(Target)**:客户端使用的接口。 - **被适配者(Adaptee)**:已有但接口不兼容的类。 - **适配器(Adapter)**:将被适配者的接口转换为目标接口。 --- ## 📌 二、适配器模式的结构 ``` +-------------------+ | Target (接口) | +-------------------+ | + request() | +-------------------+ ^ | +-------------------+ | Adapter (类) | +-------------------+ | - adaptee | | + request() | +-------------------+ ^ | +-------------------+ | Adaptee (类) | +-------------------+ | + specificRequest()| +-------------------+ ``` --- ## ✅ 三、适配器模式的优点 1. **解耦**:客户端和被适配者之间解耦,客户端只需依赖适配器。 2. **复用性**:可以复用已有的类,无需修改其代码。 3. **灵活性**:可以通过不同的适配器实现多种接口转换。 --- ## 💡 四、PHP 实现示例 ### 场景:假设我们有一个旧系统(`OldSystem`),它提供 `oldMethod()` 方法,而新系统需要使用 `newMethod()` 方法。 #### 1. 定义目标接口(Target) ```php interface NewSystem { public function newMethod(); } ``` #### 2. 被适配者(Adaptee) ```php class OldSystem { public function oldMethod() { return "Old system method called."; } } ``` #### 3. 适配器(Adapter) ```php class OldSystemAdapter implements NewSystem { private $oldSystem; public function __construct(OldSystem $oldSystem) { $this->oldSystem = $oldSystem; } public function newMethod() { // 调用旧系统的 oldMethod() return $this->oldSystem->oldMethod(); } } ``` #### 4. 使用适配器 ```php $oldSystem = new OldSystem(); $adapter = new OldSystemAdapter($oldSystem); echo $adapter->newMethod(); // 输出: Old system method called. ``` --- ## 🔄 五、适配器模式的两种形式 ### 1. 类适配器(Class Adapter) 使用继承的方式实现适配器,适合语言支持多重继承的情况(如 C++)。 ```php class OldSystemAdapter extends OldSystem implements NewSystem { public function newMethod() { return $this->oldMethod(); } } ``` > 注意:PHP 不支持多重继承,所以通常使用对象组合方式实现适配器。 --- ### 2. 对象适配器(Object Adapter) 这是更常见的实现方式,通过**组合**而非继承来实现适配。 ```php class OldSystemAdapter implements NewSystem { private $oldSystem; public function __construct(OldSystem $oldSystem) { $this->oldSystem = $oldSystem; } public function newMethod() { return $this->oldSystem->oldMethod(); } } ``` --- ## 🧠 六、适用场景 - 当你需要使用一个已经存在的类,但它的接口不符合你的需求。 - 当你想让多个类协同工作,但它们的接口不一致时。 - 当你希望统一接口来调用不同的类时。 --- ## 🧪 七、测试案例(PHPUnit 示例) ```php use PHPUnit\Framework\TestCase; class OldSystemAdapterTest extends TestCase { public function testNewMethod() { $oldSystem = new OldSystem(); $adapter = new OldSystemAdapter($oldSystem); $this->assertEquals("Old system method called.", $adapter->newMethod()); } } ``` --- ## 📘 八、总结 | 特点 | 内容 | |------|------| | 模式类型 | 结构型设计模式 | | 目的 | 将一个类的接口转换为客户端所期望的接口 | | 优点 | 解耦、复用、灵活 | | 缺点 | 增加系统复杂度(对于简单情况可能过度设计) | | 应用场景 | 接口不兼容、已有类需复用 | --- 如果你有具体的应用场景或者想了解适配器模式在 Laravel 或 Symfony 中的应用,也可以告诉我,我可以进一步讲解!
上一篇:
PHP设计模式之注册模式
下一篇:
PHP SPL 观察者模式
标题录入,一次不能超过6条
留言
评论