以下是 PHP 中常用的设计模式及其典型应用场景的整理,按模式类型分类说明:


一、创建型模式

1. 单例模式 (Singleton)

目的:确保一个类只有一个实例,并提供全局访问点。
场景:数据库连接、日志记录器、配置管理器。

  1. class Database {
  2. private static $instance = null;
  3. private function __construct() {}
  4. public static function getInstance() {
  5. if (self::$instance === null) {
  6. self::$instance = new Database();
  7. }
  8. return self::$instance;
  9. }
  10. }

2. 工厂方法模式 (Factory Method)

目的:定义创建对象的接口,由子类决定实例化哪个类。
场景:框架中对象创建(如 HTTP 请求对象)。

  1. interface PaymentProcessor {
  2. public function process($amount);
  3. }
  4. class CreditCardProcessor implements PaymentProcessor { /* ... */ }
  5. class PaymentFactory {
  6. public static function create($type) {
  7. return new CreditCardProcessor(); // 根据 $type 动态创建
  8. }
  9. }

3. 建造者模式 (Builder)

目的:分步构造复杂对象,分离对象的构造与表示。
场景:生成 HTML 表单、构建 SQL 查询。

  1. class HtmlFormBuilder {
  2. private $form = [];
  3. public function addInput($name, $type) { /* ... */ }
  4. public function build() { return new Form($this->form); }
  5. }

4. 原型模式 (Prototype)

目的:通过克隆现有对象创建新对象,减少重复初始化。
场景:缓存对象、复制复杂数据结构。

  1. class User implements Cloneable {
  2. public function __clone() {
  3. // 深拷贝逻辑
  4. }
  5. }
  6. $user = new User();
  7. $cloneUser = clone $user;

二、结构型模式

1. 适配器模式 (Adapter)

目的:使不兼容的接口能够协同工作。
场景:集成第三方库(如支付网关适配)。

  1. class PayPalAdapter implements PaymentGateway {
  2. private $paypal;
  3. public function __construct(PayPal $paypal) {
  4. $this->paypal = $paypal;
  5. }
  6. public function pay($amount) {
  7. $this->paypal->executePayment($amount);
  8. }
  9. }

2. 装饰器模式 (Decorator)

目的:动态地为对象添加职责。
场景:文件流处理(如压缩、加密)。

  1. interface Logger {
  2. public function log($message);
  3. }
  4. class FileLogger implements Logger { /* ... */ }
  5. class EncryptedLogger implements Logger {
  6. private $logger;
  7. public function __construct(Logger $logger) {
  8. $this->logger = $logger;
  9. }
  10. public function log($message) {
  11. $encrypted = encrypt($message);
  12. $this->logger->log($encrypted);
  13. }
  14. }

3. 代理模式 (Proxy)

目的:为其他对象提供代理以控制访问。
场景:延迟加载大对象、权限验证。

  1. class ImageProxy {
  2. private $image = null;
  3. public function display() {
  4. if ($this->image === null) {
  5. $this->image = new RealImage("large.jpg");
  6. }
  7. $this->image->display();
  8. }
  9. }

4. 组合模式 (Composite)

目的:将对象组合成树形结构以表示“部分-整体”层次。
场景:文件系统目录结构、菜单系统。

  1. interface FileSystemComponent {
  2. public function render();
  3. }
  4. class File implements FileSystemComponent {
  5. public function render() { /* 显示文件 */ }
  6. }
  7. class Directory implements FileSystemComponent {
  8. private $children = [];
  9. public function addComponent(FileSystemComponent $c) { /* ... */ }
  10. public function render() { /* 递归渲染子项 */ }
  11. }

三、行为型模式

1. 策略模式 (Strategy)

目的:定义一系列算法并使其可互换。
场景:支付方式切换(支付宝/微信)、排序算法选择。

  1. interface SortStrategy {
  2. public function sort(array $data);
  3. }
  4. class QuickSort implements SortStrategy { /* ... */ }
  5. class Sorter {
  6. private $strategy;
  7. public function setStrategy(SortStrategy $s) { $this->strategy = $s; }
  8. public function execute(array $data) { return $this->strategy->sort($data); }
  9. }

2. 观察者模式 (Observer)

目的:定义对象间的一对多依赖,当一个对象状态改变时自动通知依赖者。
场景:事件监听(如用户注册后发送邮件)、日志记录。

  1. class UserRegisteredEvent {
  2. private $user;
  3. public function __construct(User $u) { $this->user = $u; }
  4. }
  5. class EmailSubscriber {
  6. public function handle(UserRegisteredEvent $event) {
  7. sendEmail($event->user->email);
  8. }
  9. }

3. 命令模式 (Command)

目的:将请求封装为对象,以便参数化、队列化或记录请求。
场景:任务队列、事务回滚、宏命令。

  1. interface Command {
  2. public function execute();
  3. }
  4. class CreateUserCommand implements Command {
  5. private $userService;
  6. public function execute() { $this->userService->create(); }
  7. }
  8. class CommandQueue {
  9. private $commands = [];
  10. public function add(Command $c) { $this->commands[] = $c; }
  11. public function process() { foreach ($this->commands as $c) $c->execute(); }
  12. }

4. 责任链模式 (Chain of Responsibility)

目的:使多个对象都有机会处理请求,避免请求发送者与接收者耦合。
场景:中间件管道(如 Laravel 中间件)、审批流程。

  1. abstract class Middleware {
  2. protected $next;
  3. public function setNext(Middleware $m) { $this->next = $m; }
  4. public function handle($request) {
  5. if ($this->next) return $this->next->handle($request);
  6. }
  7. }
  8. class AuthMiddleware extends Middleware {
  9. public function handle($request) {
  10. if (!auth()->check()) throw new UnauthorizedException();
  11. parent::handle($request);
  12. }
  13. }

四、如何选择设计模式?

  1. 解耦需求:当系统需要降低模块间耦合时(如观察者模式)。
  2. 复用与扩展:需灵活扩展功能时(如装饰器模式)。
  3. 复杂流程控制:如状态模式管理订单生命周期。
  4. 代码可维护性:如策略模式替代条件分支(switch-case)。

通过合理使用设计模式,可以提升代码的可维护性、扩展性和复用性,但需避免过度设计。