当前位置:首页 > PHP

设计模式php实现

2026-02-15 20:37:55PHP

设计模式在PHP中的实现

设计模式是解决常见软件设计问题的可重用方案。在PHP中实现设计模式可以提高代码的可维护性、可扩展性和复用性。以下是几种常见设计模式及其PHP实现示例。

单例模式(Singleton)

单例模式确保一个类只有一个实例,并提供一个全局访问点。

class Singleton {
    private static $instance;

    private function __construct() {}

    public static function getInstance() {
        if (null === static::$instance) {
            static::$instance = new static();
        }
        return static::$instance;
    }

    private function __clone() {}
    private function __wakeup() {}
}

工厂模式(Factory)

工厂模式定义一个用于创建对象的接口,让子类决定实例化哪一个类。

interface Product {
    public function getName();
}

class ConcreteProductA implements Product {
    public function getName() {
        return 'Product A';
    }
}

class ConcreteProductB implements Product {
    public function getName() {
        return 'Product B';
    }
}

class ProductFactory {
    public static function createProduct($type) {
        switch ($type) {
            case 'A':
                return new ConcreteProductA();
            case 'B':
                return new ConcreteProductB();
            default:
                throw new Exception('Invalid product type');
        }
    }
}

观察者模式(Observer)

观察者模式定义对象间的一对多依赖关系,当一个对象状态改变时,所有依赖它的对象都会得到通知。

interface Observer {
    public function update($data);
}

interface Subject {
    public function attach(Observer $observer);
    public function detach(Observer $observer);
    public function notify();
}

class ConcreteSubject implements Subject {
    private $observers = [];
    private $data;

    public function attach(Observer $observer) {
        $this->observers[] = $observer;
    }

    public function detach(Observer $observer) {
        $key = array_search($observer, $this->observers, true);
        if ($key !== false) {
            unset($this->observers[$key]);
        }
    }

    public function notify() {
        foreach ($this->observers as $observer) {
            $observer->update($this->data);
        }
    }

    public function setData($data) {
        $this->data = $data;
        $this->notify();
    }
}

class ConcreteObserver implements Observer {
    public function update($data) {
        echo "Received update with data: " . $data . "\n";
    }
}

策略模式(Strategy)

策略模式定义一系列算法,将每个算法封装起来,并使它们可以互相替换。

interface PaymentStrategy {
    public function pay($amount);
}

class CreditCardPayment implements PaymentStrategy {
    public function pay($amount) {
        echo "Paying $amount via Credit Card\n";
    }
}

class PayPalPayment implements PaymentStrategy {
    public function pay($amount) {
        echo "Paying $amount via PayPal\n";
    }
}

class ShoppingCart {
    private $paymentStrategy;

    public function setPaymentStrategy(PaymentStrategy $strategy) {
        $this->paymentStrategy = $strategy;
    }

    public function checkout($amount) {
        $this->paymentStrategy->pay($amount);
    }
}

适配器模式(Adapter)

适配器模式将一个类的接口转换成客户希望的另一个接口。

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 $this->adaptee->specificRequest();
    }
}

装饰器模式(Decorator)

装饰器模式动态地给一个对象添加一些额外的职责。

interface Component {
    public function operation();
}

class ConcreteComponent implements Component {
    public function operation() {
        return "ConcreteComponent";
    }
}

abstract 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 "DecoratorA(" . parent::operation() . ")";
    }
}

class ConcreteDecoratorB extends Decorator {
    public function operation() {
        return "DecoratorB(" . parent::operation() . ")";
    }
}

设计模式的选择原则

  • 创建型模式(如单例、工厂)用于对象的创建
  • 结构型模式(如适配器、装饰器)用于类和对象的组合
  • 行为型模式(如观察者、策略)用于对象间的通信

在实际应用中,应根据具体需求选择合适的设计模式,避免过度设计。PHP的面向对象特性完全支持这些设计模式的实现,合理运用可以显著提高代码质量。

设计模式php实现

标签: 模式php
分享给朋友:

相关文章

php实现搜索功能

php实现搜索功能

实现基础搜索功能 使用PHP和MySQL实现基础的搜索功能需要结合表单提交与数据库查询。创建一个HTML表单用于接收用户输入的搜索关键词,通过PHP处理表单数据并查询数据库。 // 搜索表单 (H…

php实现递归

php实现递归

递归的基本概念 递归是一种函数调用自身的技术,适用于解决可以分解为相同子问题的问题。在PHP中,递归需要明确的终止条件(基线条件),否则会导致无限循环。 递归实现阶乘 阶乘是经典的递归案例,n! =…

git php实现

git php实现

Git 与 PHP 的集成实现 使用 PHP 执行 Git 命令 通过 PHP 的 exec()、shell_exec() 或 passthru() 函数可以直接调用 Git 命令,适用于服务器端操作…

php实现登录

php实现登录

PHP 登录功能实现 数据库连接与用户表创建 创建一个数据库连接文件 db.php,用于管理数据库连接。MySQL 示例代码如下: <?php $host = 'localhost'; $db…

php无限分类的实现

php无限分类的实现

PHP无限分类的实现 无限分类是一种常见的树形结构数据组织方式,适用于商品分类、菜单管理、地区选择等场景。以下是几种实现方法: 递归实现法 递归是最直观的实现方式,通过函数自身调用来遍历子分类。数据…

php搜索功能实现

php搜索功能实现

实现基本的PHP搜索功能 使用MySQL数据库和PHP实现简单的关键词搜索功能。需要确保数据库中有可供搜索的表和数据。 // 连接数据库 $conn = new mysqli('localhost…