PHP开发者必掌握的23种设计模式及其应用实践详解

  • admin
  • 2026-02-24 10:32:12

PHP开发者必掌握的23种设计模式及其应用实践详解

在软件开发领域,设计模式是解决常见设计问题的经典解决方案。它们不仅提升了代码的可读性和可维护性,还使得开发过程更加高效和规范。PHP作为一种广泛使用的编程语言,其开发者对设计模式的掌握尤为重要。本文将详细介绍PHP开发者必掌握的23种设计模式,并探讨它们在实际项目中的应用。

一、设计模式概述

设计模式主要分为三大类:创建型模式、结构型模式和行为型模式。

创建型模式:关注对象的创建过程,旨在提供更好的对象创建方式。

结构型模式:关注类和对象之间的组合,旨在提高系统的灵活性和可扩展性。

行为型模式:关注对象之间的通信和职责分配,旨在提高系统的交互性和可维护性。

二、23种设计模式详解

1. 工厂方法模式(Factory Method Pattern)

概述:定义一个用于创建对象的接口,让子类决定实例化哪一个类。

应用场景:当需要创建的对象种类较多,且创建逻辑较为复杂时。

PHP示例:

interface Product {

public function operation();

}

class ConcreteProductA implements Product {

public function operation() {

return "Product A";

}

}

class ConcreteProductB implements Product {

public function operation() {

return "Product B";

}

}

abstract class Creator {

abstract public function factoryMethod(): Product;

}

class ConcreteCreatorA extends Creator {

public function factoryMethod(): Product {

return new ConcreteProductA();

}

}

class ConcreteCreatorB extends Creator {

public function factoryMethod(): Product {

return new ConcreteProductB();

}

}

$creatorA = new ConcreteCreatorA();

$productA = $creatorA->factoryMethod();

echo $productA->operation(); // Output: Product A

2. 抽象工厂模式(Abstract Factory Pattern)

概述:提供一个接口,用于创建相关或依赖对象的家族,而不需要指定具体类。

应用场景:当需要创建一系列相关或互相依赖的对象时。

PHP示例:

interface AbstractFactory {

public function createProductA(): AbstractProductA;

public function createProductB(): AbstractProductB;

}

interface AbstractProductA {

public function usefulFunctionA();

}

interface AbstractProductB {

public function usefulFunctionB();

}

class ConcreteFactory1 implements AbstractFactory {

public function createProductA(): AbstractProductA {

return new ConcreteProductA1();

}

public function createProductB(): AbstractProductB {

return new ConcreteProductB1();

}

}

class ConcreteProductA1 implements AbstractProductA {

public function usefulFunctionA() {

return "The result of the product A1.";

}

}

class ConcreteProductB1 implements AbstractProductB {

public function usefulFunctionB() {

return "The result of the product B1.";

}

}

$factory = new ConcreteFactory1();

$productA = $factory->createProductA();

$productB = $factory->createProductB();

echo $productA->usefulFunctionA(); // Output: The result of the product A1.

echo $productB->usefulFunctionB(); // Output: The result of the product B1.

3. 单例模式(Singleton Pattern)

概述:确保一个类只有一个实例,并提供一个全局访问点。

应用场景:当需要共享资源,如数据库连接、日志记录等。

PHP示例:

class Singleton {

private static $instance = null;

private function __construct() {}

public static function getInstance() {

if (self::$instance === null) {

self::$instance = new Singleton();

}

return self::$instance;

}

private function __clone() {}

private function __wakeup() {}

}

$instance = Singleton::getInstance();

4. 建造者模式(Builder Pattern)

概述:将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。

应用场景:当需要创建复杂对象,且对象的创建过程需要分步骤进行时。

PHP示例:

interface Builder {

public function producePartA();

public function producePartB();

public function producePartC();

}

class ConcreteBuilder implements Builder {

private $product;

public function __construct() {

$this->product = new Product();

}

public function producePartA() {

$this->product->add("PartA");

}

public function producePartB() {

$this->product->add("PartB");

}

public function producePartC() {

$this->product->add("PartC");

}

public function getResult() {

return $this->product;

}

}

class Product {

private $parts = [];

public function add($part) {

$this->parts[] = $part;

}

public function show() {

echo "Product Parts: " . implode(", ", $this->parts);

}

}

class Director {

private $builder;

public function __construct(Builder $builder) {

$this->builder = $builder;

}

public function construct() {

$this->builder->producePartA();

$this->builder->producePartB();

$this->builder->producePartC();

}

}

$builder = new ConcreteBuilder();

$director = new Director($builder);

$director->construct();

$product = $builder->getResult();

$product->show(); // Output: Product Parts: PartA, PartB, PartC

5. 原型模式(Prototype Pattern)

概述:通过复制现有的实例来创建新的实例,而不是通过构造函数。

应用场景:当创建对象的成本较大,且对象的状态可以复制时。

PHP示例:

class Prototype {

private $property;

public function __construct($property) {

$this->property = $property;

}

public function setProperty($property) {

$this->property = $property;

}

public function getProperty() {

return $this->property;

}

public function __clone() {

// Deep copy if needed

}

}

$prototype = new Prototype("Original");

$clone = clone $prototype;

$clone->setProperty("Cloned");

echo $prototype->getProperty(); // Output: Original

echo $clone->getProperty(); // Output: Cloned

6. 适配器模式(Adapter Pattern)

概述:将一个类的接口转换成客户期望的另一个接口,使得原本接口不兼容的类可以一起工作。

应用场景:当需要使用已有类,但其接口不符合需求时。

PHP示例:

interface Target {

public function request();

}

class Adaptee {

public function specificRequest() {

return "Specific request";

}

}

class Adapter implements Target {

private $adaptee;

public function __construct(Adaptee $adaptee) {

$this->adaptee = $adaptee;

}

public function request() {

return "Adapter: " . $this->adaptee->specificRequest();

}

}

$adaptee = new Adaptee();

$adapter = new Adapter($adaptee);

echo $adapter->request(); // Output: Adapter: Specific request

7. 桥接模式(Bridge Pattern)

概述:将抽象部分与实现部分分离,使它们可以独立变化。

应用场景:当需要将抽象部分和实现部分分离,以便它们可以独立扩展时。

PHP示例:

interface Implementor {

public function operationImpl();

}

class ConcreteImplementorA implements Implementor {

public function operationImpl() {

return "ConcreteImplementorA operation";

}

}

class ConcreteImplementorB implements Implementor {

public function operationImpl() {

return "ConcreteImplementorB operation";

}

}

abstract class Abstraction {

protected $implementor;

public function __construct(Implementor $implementor) {

$this->implementor = $implementor;

}

abstract public function operation();

}

class RefinedAbstraction extends Abstraction {

public function operation() {

return "RefinedAbstraction: " . $this->implementor->operationImpl();

}

}

$implementorA = new ConcreteImplementorA();

$abstraction = new RefinedAbstraction($implementorA);

echo $abstraction->operation(); // Output: RefinedAbstraction: ConcreteImplementorA operation

8. 过滤器模式(Filter、Criteria Pattern)

概述:使用不同的标准来过滤一组对象。

应用场景:当需要根据不同的条件筛选对象时。

PHP示例:

interface Criteria {

public function meetCriteria(array $persons);

}

class Person {

private $name;

private $gender;

private $maritalStatus;

public function __construct($name, $gender, $maritalStatus) {

$this->name = $name;

$this->gender = $gender;

$this->maritalStatus = $maritalStatus;

}

public function getName() {

return $this->name;

}

public function getGender() {

return $this->gender;

}

public function getMaritalStatus() {

return $this->maritalStatus;

}

}

class CriteriaMale implements Criteria {

public function meetCriteria(array $persons) {

$malePersons = [];

foreach ($persons as $person) {

if ($person->getGender() == "Male") {

$malePersons[] = $person;

}

}

return $malePersons;

}

}

$persons = [

new Person("John", "Male", "Single"),

new Person("Jane", "Female", "Married"),

new Person("Mike", "Male", "Single")

];

$criteriaMale = new CriteriaMale();

$malePersons = $criteriaMale->meetCriteria($persons);

foreach ($malePersons as $person) {

echo $person->getName() . "\n"; // Output: John Mike

}

9. 组合模式(Composite Pattern)

概述:将对象组合成树形结构以表示“部分-整体”的层次结构。

应用场景:当需要处理树形结构的数据时。

PHP示例:

interface Component {

public function operation();

}

class Leaf implements Component {

private $name;

public function __construct($name) {

$this->name = $name;

}

public function operation() {

echo "Leaf " . $this->name . " operation\n";

}

}

class Composite implements Component {

private $children = [];

public function add(Component $component) {

$this->children[] = $component;

}

public function remove(Component $component) {

$key = array_search($component, $this->children);

if ($key !== false) {

unset($this->children[$key]);

}

}

public function operation() {

foreach ($this->children as $child) {

$child->operation();

}

}

}

$leaf1 = new Leaf("Leaf1");

$leaf2 = new Leaf("Leaf2");

$composite = new Composite();

$composite->add($leaf1);

$composite->add($leaf2);

$composite->operation(); // Output: Leaf Leaf1 operation Leaf Leaf2 operation

10. 装饰器模式(Decorator Pattern)

概述:动态地给一个对象添加一些额外的职责。

应用场景:当需要在不修改原有类的情况下扩展功能时。

PHP示例:

interface Component {

public function operation();

}

class ConcreteComponent implements Component {

public function operation() {

return "ConcreteComponent operation";

}

}

class Decorator implements Component {

protected $component;

public function __construct(Component $component) {

$this->component = $component;

}

public function operation() {

return $this->component->operation();

}

}

class ConcreteDecoratorA extends Decorator {

public function operation() {

return "ConcreteDecoratorA(" . parent::operation() . ")";

}

}

class ConcreteDecoratorB extends Decorator {

public function operation() {

return "ConcreteDecoratorB(" . parent::operation() . ")";

}

}

$component = new ConcreteComponent();

$decoratorA = new ConcreteDecoratorA($component);

$decoratorB = new ConcreteDecoratorB($decoratorA);

echo $decoratorB->operation(); // Output: ConcreteDecoratorB(ConcreteDecoratorA(ConcreteComponent operation))

11. 外观模式(Facade Pattern)

概述:为子系统中的一组接口提供一个统一的接口,使得子系统更容易使用。

应用场景:当需要简化复杂系统的使用时。

PHP示例:

class SubsystemA {

public function operationA() {

return "SubsystemA operation";

}

}

class SubsystemB {

public function operationB() {

return "SubsystemB operation";

}

}

class Facade {

private $subsystemA;

private $subsystemB;

public function __construct() {

$this->subsystemA = new SubsystemA();

$this->subsystemB = new SubsystemB();

}

public function operation() {

$result = $this->subsystemA->operationA() . "\n";

$result .= $this->subsystemB->operationB() . "\n";

return $result;

}

}

$facade = new Facade();

echo $facade->operation(); // Output: SubsystemA operation SubsystemB operation

12. 享元模式(Flyweight Pattern)

概述:运用共享技术有效地支持大量细粒度的对象。

应用场景:当需要大量相似对象时。

PHP示例:

interface Flyweight {

public function operation($extrinsicState);

}

class ConcreteFlyweight implements Flyweight {

private $intrinsicState;

public function __construct($intrinsicState) {

$this->intrinsicState = $intrinsicState;

}

public function operation($extrinsicState) {

return "IntrinsicState: " . $this->intrinsicState . ", ExtrinsicState: " . $extrinsicState;

}

}

class FlyweightFactory {

private $flyweights = [];

public function getFlyweight($key) {

if (!isset($this->flyweights[$key])) {

$this->flyweights[$key] = new ConcreteFlyweight($key);

}

return $this->flyweights[$key];

}

}

$factory = new FlyweightFactory();

$flyweightA = $factory->getFlyweight("A");

$flyweightB = $factory->getFlyweight("B");

echo $flyweightA->operation("1"); // Output: IntrinsicState: A, ExtrinsicState: 1

echo $flyweightB->operation("2"); // Output: IntrinsicState: B, ExtrinsicState: 2

13. 代理模式(Proxy Pattern)

概述:为其他对象提供一种代理以控制对这个对象的访问。

应用场景:当需要控制对某个对象的访问时。

PHP示例:

interface Subject {

public function request();

}

class RealSubject implements Subject {

public function request() {

return "RealSubject request";

}

}

class Proxy implements Subject {

private $realSubject;

public function request() {

if ($this->realSubject === null) {

$this->realSubject = new RealSubject();

}

return "Proxy: " . $this->realSubject->request();

}

}

$proxy = new Proxy();

echo $proxy->request(); // Output: Proxy: RealSubject request

14. 责任链模式(Chain of Responsibility Pattern)

概述:使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系。

应用场景:当需要多个对象处理同一请求时。

PHP示例:

interface Handler {

public function handle($request);

public function setNext(Handler $handler);

}

class ConcreteHandlerA implements Handler {

private $nextHandler;

public function handle($request) {

if ($request == "A") {

return "Handled by ConcreteHandlerA";

} elseif ($this->nextHandler !== null) {

return $this->nextHandler->handle($request);

}

return "No handler for request";

}

public function setNext(Handler $handler) {

$this->nextHandler = $handler;

}

}

class ConcreteHandlerB implements Handler {

private $nextHandler;

public function handle($request) {

if ($request == "B") {

return "Handled by ConcreteHandlerB";

} elseif ($this->nextHandler !== null) {

return $this->nextHandler->handle($request);

}

return "No handler for request";

}

public function setNext(Handler $handler) {

$this->nextHandler = $handler;

}

}

$handlerA = new ConcreteHandlerA();

$handlerB = new ConcreteHandlerB();

$handlerA->setNext($handlerB);

echo $handlerA->handle("A"); // Output: Handled by ConcreteHandlerA

echo $handlerA->handle("B"); // Output: Handled by ConcreteHandlerB

15. 命令模式(Command Pattern)

概述:将请求封装成对象,从而允许用户使用不同的请求、队列或日志请求来参数化其他对象。

应用场景:当需要将请求发送者和接收者解耦时。

PHP示例:

interface Command {

public function execute();

}

class ConcreteCommand implements Command {

private $receiver;

public function __construct(Receiver $receiver) {

$this->receiver = $receiver;

}

public function execute() {

return $this->receiver->action();

}

}

class Receiver {

public function action() {

return "Receiver action";

}

}

class Invoker {

private $command;

public function setCommand(Command $command) {

$this->command = $command;

}

public function executeCommand() {

return $this->command->execute();

}

}

$receiver = new Receiver();

$command = new ConcreteCommand($receiver);

$invoker = new Invoker();

$invoker->setCommand($command);

echo $invoker->executeCommand(); // Output: Receiver action

16. 解释器模式(Interpreter Pattern)

概述:为语言创建解释器,用来解释该语言中的句子。

应用场景:当需要实现一种语言解释器时。

PHP示例:

“`php

interface Expression {

public function interpret($context);

}

class TerminalExpression implements Expression {

private $data;

public function __construct($data) {

$this->data = $data;

}

public function interpret($context) {

if (strpos($context, $