常见的几种设计模式
好的!设计模式是软件开发中的一种经典解决方案,帮助解决常见问题并提升代码的可维护性和复用性。以下是几种常见的设计模式,以及用 PHP 实现的示例和详细说明:
1. 单例模式(Singleton Pattern)
用途: 确保一个类只有一个实例,并提供一个全局访问点。
实现代码:
<?php
class Singleton {
private static $instance = null;
// 构造函数私有,防止外部实例化
private function __construct() { }
// 禁止克隆对象
private function __clone() { }
// 获取唯一实例的方法
public static function getInstance() {
if (self::$instance === null) {
self::$instance = new Singleton();
}
return self::$instance;
}
public function doSomething() {
echo "This is Singleton Pattern!";
}
}
// 使用示例
$instance = Singleton::getInstance();
$instance->doSomething();
?>
说明:
- 特点: 保证只有一个全局实例,适用于配置类、日志类等场景。
- 实现细节: 构造方法和克隆方法私有化,并用静态变量存储实例。
2. 工厂模式(Factory Pattern)
用途: 提供创建对象的接口,而无需指定具体类。
实现代码:
<?php
interface Product {
public function getName();
}
class ProductA implements Product {
public function getName() {
return "I am Product A";
}
}
class ProductB implements Product {
public function getName() {
return "I am Product B";
}
}
class ProductFactory {
public static function create($type) {
if ($type === 'A') {
return new ProductA();
} elseif ($type === 'B') {
return new ProductB();
} else {
throw new Exception("Invalid product type");
}
}
}
// 使用示例
$product = ProductFactory::create('A');
echo $product->getName();
?>
说明:
- 特点: 将对象的创建与使用分离,使代码更灵活、更易扩展。
- 适用场景: 当对象的创建过程复杂或可能会根据输入条件生成不同类型的对象时。
3. 观察者模式(Observer Pattern)
用途: 定义对象间的一对多依赖关系,当一个对象状态发生变化时,自动通知所有依赖对象。
实现代码:
<?php
interface Observer {
public function update($message);
}
class ConcreteObserver implements Observer {
private $name;
public function __construct($name) {
$this->name = $name;
}
public function update($message) {
echo "Observer {$this->name} received message: {$message}\n";
}
}
class Subject {
private $observers = [];
public function attach(Observer $observer) {
$this->observers[] = $observer;
}
public function notify($message) {
foreach ($this->observers as $observer) {
$observer->update($message);
}
}
}
// 使用示例
$subject = new Subject();
$observer1 = new ConcreteObserver("A");
$observer2 = new ConcreteObserver("B");
$subject->attach($observer1);
$subject->attach($observer2);
$subject->notify("Hello Observers!");
?>
说明:
- 特点: 实现了发布-订阅机制,增强模块之间的解耦。
- 适用场景: 用于事件系统或需要通知多个组件的场景。
4. 策略模式(Strategy Pattern)
用途: 定义一系列算法,将每种算法封装起来,使它们可以互换。
实现代码:
<?php
interface Strategy {
public function execute($a, $b);
}
class AddStrategy implements Strategy {
public function execute($a, $b) {
return $a + $b;
}
}
class MultiplyStrategy 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(3, 5); // 输出 8
$context = new Context(new MultiplyStrategy());
echo $context->executeStrategy(3, 5); // 输出 15
?>
说明:
- 特点: 可以根据需求动态替换算法,降低代码耦合。
- 适用场景: 需要切换多种算法或行为的场景。
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: