php 经典设计模式
封面图
•
2026-04-09
•
PHP
19
0
0
0
PHP 中的经典设计模式是开发高质量、可维护和可扩展代码的重要工具。以下是一些在 PHP 开发中非常常见且实用的设计模式,它们被广泛应用于框架(如 Laravel、Symfony)和项目中。 --- ## 🧩 一、PHP 常见设计模式分类 ### 1. **创建型模式(Creational Patterns)** #### ✅ 工厂模式(Factory Pattern) **作用:** 定义一个用于创建对象的接口,但让子类决定实例化哪一个类。 ```php interface Animal { public function speak(); } class Dog implements Animal { public function speak() { echo "Woof!"; } } class Cat implements Animal { public function speak() { echo "Meow!"; } } class AnimalFactory { public static function create($type) { if ($type == 'dog') { return new Dog(); } elseif ($type == 'cat') { return new Cat(); } } } ``` #### ✅ 单例模式(Singleton Pattern) **作用:** 确保一个类只有一个实例,并提供一个全局访问点。 ```php class Database { private static $instance; private function __construct() { // 连接数据库 } public static function getInstance() { if (!self::$instance) { self::$instance = new Database(); } return self::$instance; } public function query($sql) { // 执行查询 } } ``` #### ✅ 抽象工厂模式(Abstract Factory Pattern) **作用:** 提供一个创建一系列相关或依赖对象的接口,而不需要指定其具体类。 ```php interface Shape { public function draw(); } class Circle implements Shape { public function draw() { echo "Circle::draw"; } } class Square implements Shape { public function draw() { echo "Square::draw"; } } interface ShapeFactory { public function createShape(); } class CircleFactory implements ShapeFactory { public function createShape() { return new Circle(); } } class SquareFactory implements ShapeFactory { public function createShape() { return new Square(); } } ``` --- ### 2. **结构型模式(Structural Patterns)** #### ✅ 适配器模式(Adapter Pattern) **作用:** 将一个类的接口转换成客户期望的另一个接口,使原本不兼容的类可以一起工作。 ```php interface MediaPlayer { public function play(string $audioType, string $fileName); } class AudioPlayer implements MediaPlayer { public function play(string $audioType, string $fileName) { if ($audioType == 'mp3') { echo "Playing mp3 file: $fileName"; } else { echo "Invalid media type."; } } } class MediaAdapter implements MediaPlayer { private $advancedMusicPlayer; public function __construct($audioType) { if ($audioType == 'vlc') { $this->advancedMusicPlayer = new VlcPlayer(); } elseif ($audioType == 'mp4') { $this->advancedMusicPlayer = new Mp4Player(); } } public function play(string $audioType, string $fileName) { $this->advancedMusicPlayer->play($audioType, $fileName); } } class VlcPlayer { public function play($audioType, $fileName) { echo "Playing vlc file: $fileName"; } } class Mp4Player { public function play($audioType, $fileName) { echo "Playing mp4 file: $fileName"; } } ``` --- ### 3. **行为型模式(Behavioral Patterns)** #### ✅ 观察者模式(Observer Pattern) **作用:** 定义对象间的一对多依赖关系,当一个对象改变状态时,所有依赖它的对象都会收到通知并自动更新。 ```php interface Observer { public function update($message); } class User implements Observer { public function update($message) { echo "User received: $message\n"; } } class Subject { private $observers = []; public function addObserver(Observer $observer) { $this->observers[] = $observer; } public function notify($message) { foreach ($this->observers as $observer) { $observer->update($message); } } } ``` #### ✅ 策略模式(Strategy Pattern) **作用:** 定义一系列算法,把它们封装起来,并且使它们可以互相替换。 ```php interface PaymentStrategy { public function pay($amount); } class CreditCardPayment implements PaymentStrategy { public function pay($amount) { echo "Paid $amount using Credit Card.\n"; } } class PayPalPayment implements PaymentStrategy { public function pay($amount) { echo "Paid $amount using PayPal.\n"; } } class PaymentContext { private $strategy; public function setStrategy(PaymentStrategy $strategy) { $this->strategy = $strategy; } public function executePayment($amount) { $this->strategy->pay($amount); } } ``` --- ## 🧠 二、PHP 中常用的设计模式总结 | 模式名称 | 类型 | 用途说明 | |------------------|------------|----------| | 工厂模式 | 创建型 | 创建对象的接口,解耦对象创建逻辑 | | 单例模式 | 创建型 | 控制对象的唯一实例 | | 适配器模式 | 结构型 | 兼容不同接口 | | 观察者模式 | 行为型 | 一对多通信机制 | | 策略模式 | 行为型 | 动态切换算法或行为 | --- ## 📦 三、PHP 框架中的设计模式应用 - **Laravel** 使用了: - **依赖注入(Dependency Injection)** - **服务容器(Service Container)** - **门面模式(Facade)** - **策略模式(Strategy)** - **Symfony** 使用了: - **事件系统(Event Dispatcher) → 观察者模式** - **服务容器(Service Container)** - **命令模式(Command Pattern)** --- ## 📌 四、推荐学习资源 - 《设计模式:可复用面向对象软件的基础》 —— GoF(Gang of Four) - [https://refactoring.guru/design-patterns](https://refactoring.guru/design-patterns) - PHP 设计模式教程(YouTube / B站) --- 如果你有特定的项目场景或想要了解某个设计模式的详细实现,欢迎继续提问!
上一篇:
php 继承与接口
下一篇:
php API 请求签名
标题录入,一次不能超过6条
留言
评论