当前位置: 首页 > 编程文章 >

PHP中常用的3种设计模式:单例、工厂与观察者详解

PHP中常用的3种设计模式:单例、工厂与观察者详解

作者:陈言时间:2025-11-04 12:27:17浏览:866

本文介绍PHP开发中常用的三种设计模式:单例模式、工厂模式和观察者模式。单例模式确保类仅有一个实例,适用于管理共享资源;工厂模式在编译时未知具体类的情况下创建对象,提升代码灵活性;观察者模式定义一对多依赖关系,实现状态变更时的自动通知。文章分析了各模式的优缺点及适用场景,帮助开发者编写更清晰、可维护的代码。

本文目录展开

什么是设计模式

设计模式是解决软件开发中常见问题的通用且可复用的方案。它们不局限于特定编程语言或框架,而是阐述了适用于多种情境的一般原则与最佳实践。应用设计模式有助于提升代码质量。

  • 增强代码的可读性与可维护性
  • 降低代码的复杂度及模块间的耦合程度
  • 提升代码的可重用性与可扩展能力
  • 强化代码的可测试性与运行可靠性

单例模式

单例模式的核心在于保证一个类在整个应用程序生命周期内仅存在一个实例。该模式常用于控制对数据库连接、配置文件或日志记录器等共享资源的访问。其具备三个关键特征:

  • 通过私有构造函数防止外部直接实例化该类
  • 利用静态属性保存唯一的类实例
  • 提供公共静态方法以返回该唯一实例

以下示例展示了如何在 PHP 中实现单例模式:

<?php
// Define a class with a private constructor
class Database {
  // Declare a static property to hold the single instance
  private static $instance = null;
  // Declare a private constructor to prevent creating new instances
  private function __construct() {
    // Connect to the database here
  }
  // Declare a public static method to get the single instance
  public static function getInstance() {
    // Check if the instance is null
    if (self::$instance == null) {
      // Create a new instance and assign it to the property
      self::$instance = new Database();
    }
    // Return the instance
    return self::$instance;
  }
}
// Get the single instance of the Database class
$db = Database::getInstance();
// Use the instance as needed
$db->query("SELECT * FROM users");

通过此示例可见,单例模式能有效避免重复建立数据库连接,从而优化性能并减少错误。同时,它有助于集中管理和配置共享资源。然而,单例模式也存在若干弊端:

  • 可能引入全局状态和隐蔽的依赖项,增加测试与调试难度
  • 可能违背单一职责原则,因为类需同时处理业务逻辑与自身实例化管理
  • 降低代码灵活性,难以适应需求变化,因无法轻松替换或扩展单一实例

因此,应谨慎使用单例模式,仅在真正必要时采用。建议考虑依赖注入或服务容器等替代方案,以实现更优的设计效果。

工厂模式

工厂模式允许在不指定具体类的情况下创建对象。当需要根据用户输入、配置设置或环境变量等条件生成不同类型的对象时,该模式尤为适用。其主要包含两个组成部分:

  • 定义对象公共行为的抽象接口或基类
  • 根据特定条件创建并返回对象的工厂类或静态方法

以下示例展示了如何在 PHP 中实现工厂模式:

<?php
// Define an abstract interface for shapes
interface Shape {
  // Declare an abstract method to draw the shape
  public function draw();
}
// Define a concrete class for circles that implements the Shape interface
class Circle implements Shape {
  // Declare a property to store the radius
  private $radius;
  // Declare a constructor to initialize the radius
  public function __construct($radius) {
    $this->radius = $radius;
  }
  // Implement the draw method to print the circle
  public function draw() {
    echo "Drawing a circle with radius " . $this->radius . "\n";
  }
}
// Define a concrete class for squares that implements the Shape interface
class Square implements Shape {
  // Declare a property to store the side length
  private $side;
  // Declare a constructor to initialize the side length
  public function __construct($side) {
    $this->side = $side;
  }
  // Implement the draw method to print the square
  public function draw() {
    echo "Drawing a square with side length " . $this->side . "\n";
  }
}
// Define a static method to create and return shapes based on a parameter
class ShapeFactory {
  // Declare a static method that takes a shape name and an optional size as parameters
  public static function createShape($name, $size = 1) {
    // Switch on the shape name
    switch ($name) {
      // If it is circle, return a new Circle object with the size as radius
      case "circle":
        return new Circle($size);
      // If it is square, return a new Square object with the size as side length
      case "square":
        return new Square($size);
      // If it is anything else, throw an exception
      default:
        throw new Exception("Invalid shape name: " . $name);
    }
  }
}
// Use the factory method to create and use different shapes
$circle = ShapeFactory::createShape("circle", 2);
$square = ShapeFactory::createShape("square", 3);
$circle->draw();
$square->draw();

工厂模式能通过以下方式促进代码的灵活性与可维护性:

  • 将对象创建逻辑与其使用场景分离,便于在不影响现有代码的前提下修改或新增对象类型
  • 将创建逻辑封装于统一位置,简化测试与调试过程
  • 向客户端隐藏创建对象的复杂细节,使代码更加简洁清晰

然而,工厂模式也存在一些不足之处:

  • 可能增加系统中的类和方法数量,导致代码体积与复杂度上升
  • 可能降低代码的表现力与直观性,因需使用通用名称和参数而非特定标识
  • 可能削弱类型安全性,因需依赖字符串或常量来指定对象类型

因此,当拥有清晰稳定的标准来创建不同对象时,可使用工厂模式。也可考虑抽象工厂或构建器模式作为替代,以实现不同抽象层级的类似效果。

观察者模式

观察者模式用于在多个对象间建立一对多关系,当一个对象状态改变时,所有依赖它的对象都会自动收到通知并更新。这在实现发布-订阅机制(如新闻通讯、聊天应用或股市数据推送)时非常有用。该模式包含两个主要部分:

  • 维护观察者列表并在状态变更时通知它们的主题或发布者
  • 向主题注册并定义通知处理方法的观察者或订阅者

以下示例展示了如何在 PHP 中实现观察者模式:

<?php
// Define an interface for subjects
interface Subject {
  // Declare a method to attach an observer to the subject
  public function attach(Observer $observer);
  // Declare a method to detach an observer from the subject
  public function detach(Observer $observer);
  // Declare a method to notify all the observers of a state change
  public function notify();
}
// Define an interface for observers
interface Observer {
  // Declare a method to update the observer with the new state of the subject
  public function update(Subject $subject);
}
// Define a concrete class for newsletters that implements the Subject interface
class Newsletter implements Subject {
  // Declare a property to store the list of observers
  private $observers = array();
  // Declare a property to store the latest news
  private $news;
  // Implement the attach method to add an observer to the list
  public function attach(Observer $observer) {
    $this->observers[] = $observer;
  }
  // Implement the detach method to remove an observer from the list
  public function detach(Observer $observer) {
    $key = array_search($observer, $this->observers, true);
    if ($key !== false) {
      unset($this->observers[$key]);
    }
  }
  // Implement the notify method to loop through the list and call the update method on each observer
  public function notify() {
    foreach ($this->observers as $observer) {
      $observer->update($this);
    }
  }
  // Declare a method to set the latest news and notify the observers
  public function setNews($news) {
    $this->news = $news;
    $this->notify();
  }
  // Declare a method to get the latest news
  public function getNews() {
    return $this->news;
  }
}
// Define a concrete class for email subscribers that implements the Observer interface
class EmailSubscriber implements Observer {
  // Declare a property to store the email address
  private $email;
  // Declare a constructor to initialize the email address
  public function __construct($email) {
    $this->email = $email;
  }
  // Implement the update method to print the email address and the latest news from the subject
  public function update(Subject $subject) {
    echo "Sending email to " . $this->email . " with news: " . $subject->getNews() . "\n";
  }
}
// Create a new newsletter object
$newsletter = new Newsletter();
// Create some email subscriber objects and attach them to the newsletter object
$subscriber1 = new EmailSubscriber("alice@example.com");
$subscriber2 = new EmailSubscriber("bob@example.com");
$subscriber3 = new EmailSubscriber("charlie@example.com");
$newsletter->attach($subscriber1);
$newsletter->attach($subscriber2);
$newsletter->attach($subscriber3);
// Set some news and see how the subscribers are notified
$newsletter->setNews("PHP Design Patterns are Awesome!");
$newsletter->setNews("Learn More About PHP Design Patterns Here!");
// Detach one subscriber and set some more news and see how only the remaining subscribers are notified
$newsletter->detach($subscriber2);
$newsletter->setNews("Don't Miss This Amazing Offer on PHP Design Patterns!");

观察者模式能通过以下方式促进代码的模块化与解耦:

  • 分离主题与观察者的关注点,允许在不影响主题的情况下增减观察者类型
  • 支持事件驱动架构,提升代码的响应速度与动态特性
  • 促进松耦合与高内聚,使代码更易维护与复用

然而,观察者模式也存在潜在缺陷:

  • 若未妥善管理主题与观察者间的引用,可能导致内存泄漏及性能问题
  • 可能增加理解与调试难度,因需追踪多个对象及其跨模块交互
  • 若未处理循环依赖或递归通知,可能引发意外副作用或无限循环

因此,当对事件与通知有清晰一致的定义时,可使用观察者模式。也可考虑使用 PHP 内置的 SplSubject 和 SplObserver 等支持该模式的库功能。

总结

设计模式并非解决所有问题的万能钥匙,而是辅助编写优质代码的工具。开发者应遵循经过验证的原则与最佳实践,谨慎且深入地理解这些模式,并根据具体需求与环境进行调整应用。

以上就是浅谈PHP中常用的3种设计模式的详细内容,更多关于PHP 设计模式的资料请关注本站其它相关文章!

上一篇
PHP门面模式实现简单的邮件发送示例

本文介绍如何使用PHP的门面模式(Facade)结合PHPMailer库实现结构化的邮件发送功能。通过定义统一接口,客户端无需关心底层复杂的SMTP配置、参数校验及异常处理逻辑。文章详细展示了从环境配置(如开启SSL扩展)、QQ邮箱授权码获取到代码分层实现的完整流程,帮助开发者降低耦合度并提升代码可维护性。

下一篇
PHP高并发场景下的缓存失效、接口幂等性与库存超卖解决方案

本文针对PHP在高并发和高负载环境下常见的三个典型问题提供实战解决方案。首先,通过配置Redis的键空间通知(Keyspace Notifications)订阅键失效事件,实现缓存自动刷新或替代定时任务处理业务到期逻辑。其次,利用Redis原子命令setnx解决注册等接口的重复提交问题,确保数据操作的幂等性。最后,结合数据库字段无符号约束与version版本号机制,采用乐观锁策略防止秒杀场景中的库存超卖现象,保障数据一致性。

相关文章

更多
《Head First 设计模式》PHP版代码解析:策略、单件与工厂模式

本文基于《Head First 设计模式》提供PHP版本的代码示例,涵盖策略模式、单件模式和工厂方法模式。通过定义飞行与呱呱叫行为接口,演示算法族如何封装并互相替换;展示确保类唯一实例的全局访问点实现;并以披萨店为例,对比直接创建对象与通过抽象工厂创建食材的两种工厂方法差异,帮助理解面向对象编程中的解耦技巧。

2025.06.14 943
PHP设计模式详解:建造者模式(Builder)原理与实例

本文深入解析PHP中的建造者模式(Builder),通过肯德基套餐和工资计算等实例,阐明其将复杂对象构建与表示分离的核心思想。详细阐述模式的组成角色、适用场景及三大优势,并对比其与工厂模式的区别,提供完整的PHP代码实现以供参考。

2026.03.26 825
PHP对象克隆clone与__clone魔术方法详解及单例模式保护

本文深入解析PHP中对象克隆机制。介绍使用clone关键字复制对象的方法,以及通过__clone魔术方法在克隆时重新初始化属性。同时演示如何利用private修饰的__clone方法禁止单例类被克隆,确保单例模式的唯一性。

2025.04.19 813
PHP设计模式详解:工厂模式(Factory Method)的实现与解析

本文深入解析PHP中的工厂模式(Factory Method),该模式定义一个创建对象的接口,让子类决定实例化哪一个类。文章详细阐述了抽象产品、具体产品、抽象工厂和具体工厂四个核心角色,分析了其在扩展新产品时符合开放-封闭原则的优势,以及可能增加子类数量的缺点。通过对比简单工厂模式,说明了工厂方法在多态性上的特点,并提供了完整的PHP代码示例以辅助理解。

2026.01.21 760
PHP单例模式实现:防止继承与克隆

本文深入解析PHP单例模式的实现细节,重点阐述如何通过技术手段防止类被意外继承或克隆,确保全局唯一实例的严格性。提供具体代码示例供开发者参考,帮助掌握核心设计模式的应用。

2026.11.03 694
PHP装饰者模式详解:原理、角色与实战案例

本文深入解析PHP中的装饰者模式,阐述其作为结构型模式如何通过包装现有对象来动态添加新功能。文章详细拆解抽象构件、具体构件、装饰者及具体装饰者四大核心角色,并结合完整的代码示例演示如何构建请求处理过滤器链,最后总结该模式的优缺点及其在替代继承扩展方面的优势。

2026.02.04 646

专题推荐

更多
PHP 类与对象定义及继承

先看类声明、对象实例与属性访问。理解对象的创建和销毁后,再读继承、方法重载和关键字对照。已有代码遇到继承行为差异时,可进一步查看 final 方法与反射实例。

PHP 定时任务配置与运行

先确定任务运行间隔以及是否允许重叠。固定时间触发先看 Cron 案例,框架内和常驻服务再读对应示例。

Yii2 队列配置与常驻运行

先用一个最小任务跑通入队和消费,再检查 Web 与 Console 是否加载了相同的队列配置。确认命令能手动运行后再配置 Supervisor,最后验证进程重启时的处理情况。

PHP Session 过期时间设置方法

浏览器关闭、服务端回收和业务规定的闲置超时,可能在不同时间发生。对照配置项与应用层时间戳的做法,检查会话何时仍可读、何时应要求重新登录。

PHP URL 编码和解码方法

URL 路径片段和查询参数对空格的处理方式不同。先比较 urlencode 与 rawurlencode,再沿解码过程核对中文、加号和百分号,检查地址是否被重复编码或提前解码。

在线工具箱

更多
键码查询
键码查询

按下键盘按键时查看浏览器记录的键名和事件信息。

.env 配置检查
.env 配置检查

本地检查 .env 键值语法、引号、重复键及空值,预览解析结果,辅助排查 PHP 和 Laravel 环境配置。

进制转换
进制转换

转换二进制、十进制、十六进制等数值表示,辅助程序调试与进制学习。

HTML 标签安全清理
HTML 标签安全清理

清理 HTML 片段中的标签或危险内容,辅助整理待展示的文本。

文件 Base64 转换
文件 Base64 转换

把文件转为 Base64 文本,也可将编码内容还原为文件,方便接口传输与调试。