PHP设计模式源码
PHP设计模式是一种在软件工程中常用的编程技巧,用于解决常见的软件设计问题,以下是一些常见的PHP设计模式及其源码示例:
(图片来源网络,侵删)
单例模式(Singleton)
单例模式确保一个类只有一个实例,并提供全局访问点。
class Singleton { private static $instance = null; private function __construct() { // 防止通过反射或序列化创建新的实例 if (self::$instance) { throw new Exception("Cannot instantiate singleton class"); } } public static function getInstance() { if (!self::$instance) { self::$instance = new Singleton(); } return self::$instance; } private function __clone() {} private function __wakeup() {} } // 使用示例 $singleton1 = Singleton::getInstance(); $singleton2 = Singleton::getInstance(); if ($singleton1 === $singleton2) { echo "Singleton works!"; } else { echo "Singleton failed!"; }
工厂模式(Factory)
工厂模式用于创建对象,而不直接使用new关键字,这使得代码更易于测试和扩展。
interface Product { public function create(); } class ConcreteProductA implements Product { public function create() { return new ConcreteProductA(); } } class ConcreteProductB implements Product { public function create() { return new ConcreteProductB(); } } class ProductFactory { public static function createProduct(string $type): Product { switch ($type) { case 'A': return new ConcreteProductA(); case 'B': return new ConcreteProductB(); default: throw new Exception("Invalid product type"); } } } // 使用示例 $productA = ProductFactory::createProduct('A'); $productB = ProductFactory::createProduct('B');
观察者模式(Observer)
(图片来源网络,侵删)
观察者模式定义了对象之间的一对多依赖关系,当一个对象改变状态时,它的所有依赖者都会收到通知并自动更新。
interface Observer { public function update(Subject $subject); } interface Subject { public function registerObserver(Observer $observer); public function removeObserver(Observer $observer); public function notifyObservers(); } class ConcreteSubject implements Subject { private $observers = []; public function registerObserver(Observer $observer) { $this->observers[] = $observer; } public function removeObserver(Observer $observer) { $index = array_search($observer, $this->observers); if ($index !== false) { unset($this->observers[$index]); } } public function notifyObservers() { foreach ($this->observers as $observer) { $observer->update($this); } } } class ConcreteObserver implements Observer { public function update(Subject $subject) { echo "Observer updated with subject state."; } } // 使用示例 $subject = new ConcreteSubject(); $observer1 = new ConcreteObserver(); $observer2 = new ConcreteObserver(); $subject->registerObserver($observer1); $subject->registerObserver($observer2); $subject->notifyObservers(); // Both observers will be notified and print the message.
(图片来源网络,侵删)
本文来源于互联网,如若侵权,请联系管理员删除,本文链接:https://www.9969.net/59582.html