当前位置:首页 > PHP

php设计模式实现

2026-02-16 18:36:14PHP

单例模式(Singleton)

单例模式确保一个类只有一个实例,并提供一个全局访问点。适用于数据库连接、日志记录等场景。

class Singleton {
    private static $instance;

    private function __construct() {
        // 私有化构造方法防止外部实例化
    }

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

    private function __clone() {
        // 防止克隆
    }
}

// 使用
$instance = Singleton::getInstance();

工厂模式(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 Factory {
    public static function createProduct($type) {
        switch ($type) {
            case 'A':
                return new ConcreteProductA();
            case 'B':
                return new ConcreteProductB();
            default:
                throw new Exception("Invalid product type");
        }
    }
}

// 使用
$product = Factory::createProduct('A');
echo $product->getName(); // 输出 "Product A"

观察者模式(Observer)

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

php设计模式实现

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

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

class Subject {
    private $observers = [];

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

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

// 使用
$subject = new Subject();
$observer = new ConcreteObserver();
$subject->attach($observer);
$subject->notify("Some data");

策略模式(Strategy)

策略模式定义一系列算法,将每个算法封装起来并使它们可以互换。适用于需要动态切换算法的场景。

interface Strategy {
    public function execute($a, $b);
}

class AddStrategy implements Strategy {
    public function execute($a, $b) {
        return $a + $b;
    }
}

class SubtractStrategy implements Strategy {
    public function execute($a, $b) {
        return $a - $b;
    }
}

class Context {
    private $strategy;

    public function __construct(Strategy $strategy) {
        $this->strategy = $strategy;
    }

    public function executeStrategy($a, $b) {
        return $this->strategy->execute($a, $b);
    }
}

// 使用
$context = new Context(new AddStrategy());
echo $context->executeStrategy(5, 3); // 输出 8

适配器模式(Adapter)

适配器模式将一个类的接口转换成客户希望的另一个接口,使原本不兼容的类可以一起工作。

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

// 使用
$adaptee = new Adaptee();
$adapter = new Adapter($adaptee);
echo $adapter->request(); // 输出 "Specific request"

装饰器模式(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() . ")";
    }
}

// 使用
$component = new ConcreteComponent();
$decoratorA = new ConcreteDecoratorA($component);
$decoratorB = new ConcreteDecoratorB($decoratorA);
echo $decoratorB->operation(); // 输出 "DecoratorB(DecoratorA(ConcreteComponent))"

责任链模式(Chain of Responsibility)

责任链模式使多个对象都有机会处理请求,从而避免请求发送者和接收者之间的耦合。

abstract class Handler {
    protected $successor;

    public function setSuccessor(Handler $successor) {
        $this->successor = $successor;
    }

    abstract public function handleRequest($request);
}

class ConcreteHandlerA extends Handler {
    public function handleRequest($request) {
        if ($request === 'A') {
            return "Handled by A";
        } elseif ($this->successor !== null) {
            return $this->successor->handleRequest($request);
        }
        return null;
    }
}

class ConcreteHandlerB extends Handler {
    public function handleRequest($request) {
        if ($request === 'B') {
            return "Handled by B";
        } elseif ($this->successor !== null) {
            return $this->successor->handleRequest($request);
        }
        return null;
    }
}

// 使用
$handlerA = new ConcreteHandlerA();
$handlerB = new ConcreteHandlerB();
$handlerA->setSuccessor($handlerB);
echo $handlerA->handleRequest('B'); // 输出 "Handled by B"

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

相关文章

php实现图片上传

php实现图片上传

实现图片上传的基本步骤 创建HTML表单用于文件上传,表单需设置enctype="multipart/form-data"属性,确保文件数据正确传输。 <form action="upload…

php购物车实现

php购物车实现

PHP购物车实现方法 使用PHP实现购物车功能可以通过多种方式完成,以下是几种常见的实现方法: Session存储购物车数据 利用PHP的$_SESSION超全局变量存储购物车数据是最简单的方法。用…

php实现聊天

php实现聊天

实现 PHP 聊天功能的方法 使用 WebSocket 和 PHP 实现实时聊天 WebSocket 是一种全双工通信协议,适合实现实时聊天功能。PHP 可以通过 Ratchet 库实现 WebSo…

php 实现秒杀

php 实现秒杀

PHP 实现秒杀的关键技术 秒杀系统需要解决高并发、超卖、性能瓶颈等问题。以下是实现秒杀的核心方案: 使用 Redis 预减库存 将商品库存提前加载到 Redis 中,通过原子操作保证库存准确性:…

php 实现下载

php 实现下载

PHP 实现文件下载的方法 使用 PHP 实现文件下载可以通过设置 HTTP 头信息,强制浏览器将文件作为附件下载而非直接打开。 基本下载实现 $file_path = 'path/to/your/…

php 实现单链表

php 实现单链表

单链表的基本概念 单链表是一种线性数据结构,由节点组成,每个节点包含数据域和指向下一个节点的指针域。链表的头节点是访问整个链表的入口。 单链表的节点类实现 在PHP中,可以通过类来定义链表节点。每个…