以下是 PHP 中常用的设计模式及其典型应用场景的整理,按模式类型分类说明:
一、创建型模式
1. 单例模式 (Singleton)
目的:确保一个类只有一个实例,并提供全局访问点。
场景:数据库连接、日志记录器、配置管理器。
class Database {private static $instance = null;private function __construct() {}public static function getInstance() {if (self::$instance === null) {self::$instance = new Database();}return self::$instance;}}
2. 工厂方法模式 (Factory Method)
目的:定义创建对象的接口,由子类决定实例化哪个类。
场景:框架中对象创建(如 HTTP 请求对象)。
interface PaymentProcessor {public function process($amount);}class CreditCardProcessor implements PaymentProcessor { /* ... */ }class PaymentFactory {public static function create($type) {return new CreditCardProcessor(); // 根据 $type 动态创建}}
3. 建造者模式 (Builder)
目的:分步构造复杂对象,分离对象的构造与表示。
场景:生成 HTML 表单、构建 SQL 查询。
class HtmlFormBuilder {private $form = [];public function addInput($name, $type) { /* ... */ }public function build() { return new Form($this->form); }}
4. 原型模式 (Prototype)
目的:通过克隆现有对象创建新对象,减少重复初始化。
场景:缓存对象、复制复杂数据结构。
class User implements Cloneable {public function __clone() {// 深拷贝逻辑}}$user = new User();$cloneUser = clone $user;
二、结构型模式
1. 适配器模式 (Adapter)
目的:使不兼容的接口能够协同工作。
场景:集成第三方库(如支付网关适配)。
class PayPalAdapter implements PaymentGateway {private $paypal;public function __construct(PayPal $paypal) {$this->paypal = $paypal;}public function pay($amount) {$this->paypal->executePayment($amount);}}
2. 装饰器模式 (Decorator)
目的:动态地为对象添加职责。
场景:文件流处理(如压缩、加密)。
interface Logger {public function log($message);}class FileLogger implements Logger { /* ... */ }class EncryptedLogger implements Logger {private $logger;public function __construct(Logger $logger) {$this->logger = $logger;}public function log($message) {$encrypted = encrypt($message);$this->logger->log($encrypted);}}
3. 代理模式 (Proxy)
目的:为其他对象提供代理以控制访问。
场景:延迟加载大对象、权限验证。
class ImageProxy {private $image = null;public function display() {if ($this->image === null) {$this->image = new RealImage("large.jpg");}$this->image->display();}}
4. 组合模式 (Composite)
目的:将对象组合成树形结构以表示“部分-整体”层次。
场景:文件系统目录结构、菜单系统。
interface FileSystemComponent {public function render();}class File implements FileSystemComponent {public function render() { /* 显示文件 */ }}class Directory implements FileSystemComponent {private $children = [];public function addComponent(FileSystemComponent $c) { /* ... */ }public function render() { /* 递归渲染子项 */ }}
三、行为型模式
1. 策略模式 (Strategy)
目的:定义一系列算法并使其可互换。
场景:支付方式切换(支付宝/微信)、排序算法选择。
interface SortStrategy {public function sort(array $data);}class QuickSort implements SortStrategy { /* ... */ }class Sorter {private $strategy;public function setStrategy(SortStrategy $s) { $this->strategy = $s; }public function execute(array $data) { return $this->strategy->sort($data); }}
2. 观察者模式 (Observer)
目的:定义对象间的一对多依赖,当一个对象状态改变时自动通知依赖者。
场景:事件监听(如用户注册后发送邮件)、日志记录。
class UserRegisteredEvent {private $user;public function __construct(User $u) { $this->user = $u; }}class EmailSubscriber {public function handle(UserRegisteredEvent $event) {sendEmail($event->user->email);}}
3. 命令模式 (Command)
目的:将请求封装为对象,以便参数化、队列化或记录请求。
场景:任务队列、事务回滚、宏命令。
interface Command {public function execute();}class CreateUserCommand implements Command {private $userService;public function execute() { $this->userService->create(); }}class CommandQueue {private $commands = [];public function add(Command $c) { $this->commands[] = $c; }public function process() { foreach ($this->commands as $c) $c->execute(); }}
4. 责任链模式 (Chain of Responsibility)
目的:使多个对象都有机会处理请求,避免请求发送者与接收者耦合。
场景:中间件管道(如 Laravel 中间件)、审批流程。
abstract class Middleware {protected $next;public function setNext(Middleware $m) { $this->next = $m; }public function handle($request) {if ($this->next) return $this->next->handle($request);}}class AuthMiddleware extends Middleware {public function handle($request) {if (!auth()->check()) throw new UnauthorizedException();parent::handle($request);}}
四、如何选择设计模式?
- 解耦需求:当系统需要降低模块间耦合时(如观察者模式)。
- 复用与扩展:需灵活扩展功能时(如装饰器模式)。
- 复杂流程控制:如状态模式管理订单生命周期。
- 代码可维护性:如策略模式替代条件分支(switch-case)。
通过合理使用设计模式,可以提升代码的可维护性、扩展性和复用性,但需避免过度设计。
