当前位置:首页 > 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)

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

设计模式php实现

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)

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

设计模式php实现

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 中实现定时任务可以通过多种方式完成,具体选择取决于项目需求和服务器环境。以下是常见的实现方法: 使用 Cron 任务 Cron 是 Linux 系统中常用…

php如何实现直播

php如何实现直播

实现直播功能的方法 PHP可以通过结合其他技术和工具来实现直播功能。以下是几种常见的方法: 使用流媒体服务器 配置流媒体服务器如Nginx-RTMP、Red5或Wowza。这些服务器支持RTMP协…

php实现静态

php实现静态

静态化实现方法 PHP实现静态化主要通过生成HTML文件或缓存机制来减少服务器动态解析的开销。以下是几种常见方法: 生成静态HTML文件 通过file_put_contents()将动态内容保存为H…

php实现一个

php实现一个

PHP 实现一个简单的计算器 创建一个基本的计算器,支持加、减、乘、除运算。以下是一个完整的实现代码示例: <?php $result = ""; if ($_SERVER["REQUES…

php 实现多继承

php 实现多继承

在PHP中,原生不支持多继承,但可以通过以下几种方法模拟实现类似多继承的功能: 使用 trait Trait是PHP 5.4引入的特性,允许在类中复用代码片段,可以视为一种轻量级的继承机制。一个类可…

php实现获取验证码

php实现获取验证码

使用GD库生成验证码 在PHP中,可以通过GD库来生成验证码图片。以下是一个简单的实现示例: <?php session_start(); $width = 120; $height = 40…