php实现模式
PHP 设计模式实现
PHP 中常用的设计模式包括单例模式、工厂模式、观察者模式等。以下是几种常见设计模式的实现方法。
单例模式
单例模式确保一个类只有一个实例,并提供全局访问点。

class Singleton {
private static $instance;
private function __construct() {
// 私有构造函数防止外部实例化
}
public static function getInstance() {
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
private function __clone() {
// 防止克隆
}
private function __wakeup() {
// 防止反序列化
}
}
$instance1 = Singleton::getInstance();
$instance2 = Singleton::getInstance();
var_dump($instance1 === $instance2); // 输出 true
工厂模式
工厂模式通过一个工厂类创建对象,而不是直接实例化具体类。

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 InvalidArgumentException("Unknown product type");
}
}
}
$productA = ProductFactory::createProduct('A');
echo $productA->getName(); // 输出 Product A
观察者模式
观察者模式定义对象间的一对多依赖关系,当一个对象状态改变时,所有依赖它的对象都会得到通知。
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) {
$index = array_search($observer, $this->observers);
if ($index !== false) {
unset($this->observers[$index]);
}
}
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 "Observer received data: " . $data . "\n";
}
}
$subject = new ConcreteSubject();
$observer = new ConcreteObserver();
$subject->attach($observer);
$subject->setData("Hello World"); // 输出 Observer received data: Hello World
策略模式
策略模式定义一系列算法,将每个算法封装起来,并使它们可以互换。
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
$context = new Context(new SubtractStrategy());
echo $context->executeStrategy(5, 3); // 输出 2
这些模式可以帮助解决特定问题,提高代码的可维护性和扩展性。根据具体需求选择合适的模式。






