函数设计模式提高了 php 代码的可重用性和可维护性。本文介绍了四种常见模式:单例模式:确保只有一个实例。工厂模式:创建特定类型的对象。观察者模式:当主题状态改变时通知观察者。策略模式:互换使用算法而不改变客户端代码。

PHP 函数设计模式应用案例分析
函数设计模式是一种组织函数代码的方式,可提高代码可重用性和可维护性。本文将介绍 PHP 中常见的函数设计模式,并通过实战案例演示其应用。
一、单例模式
立即学习“PHP免费学习笔记(深入)”;
单例模式确保一个类只有一个实例。例如,创建一个数据库连接对象:
class DatabaseConnection {
private static $instance;
private function __construct() {}
public static function getInstance() {
if (!isset(self::$instance)) {
self::$instance = new self();
}
return self::$instance;
}
}
// 获取数据库连接
$connection = DatabaseConnection::getInstance();二、工厂模式
工厂模式创建对象的特定实例,而不指定其具体类。它提供了一种动态创建对象的方法,以便客户端代码无需了解具体的类实现。
interface Shape {
public function draw();
}
class Circle implements Shape {
public function draw() { echo "Drawing a circle\n"; }
}
class Square implements Shape {
public function draw() { echo "Drawing a square\n"; }
}
class ShapeFactory {
public static function create($type) {
switch ($type) {
case 'circle': return new Circle();
case 'square': return new Square();
default: throw new Exception('Invalid shape type');
}
}
}
// 创建一个圆形
$circle = ShapeFactory::create('circle');
$circle->draw(); // 输出:Drawing a circle三、观察者模式
观察者模式定义了一个一个对一个或一对多的依赖关系,当一个对象(主题)的状态发生改变时,所有依赖它的对象(观察者)都会被通知。
class Subject {
private $observers = [];
public function attach($observer) {
$this->observers[] = $observer;
}
public function notify() {
foreach ($this->observers as $observer) {
$observer->update($this);
}
}
}
class Observer {
public function update($subject) {
echo "Observer notified\n";
}
}
// 创建一个主题和两个观察者
$subject = new Subject();
$observer1 = new Observer();
$observer2 = new Observer();
// 将观察者附加到主题
$subject->attach($observer1);
$subject->attach($observer2);
// 当主题的状态发生改变时,通知所有观察者
$subject->notify(); // 输出:Observer notified\nObserver notified\n四、策略模式
策略模式定义了一组相关算法,以便算法可以互换地使用,而无需更改客户端代码。
interface PaymentStrategy {
public function calculateTotal($order);
}
class CashPaymentStrategy implements PaymentStrategy {
public function calculateTotal($order) {
return $order->getTotal();
}
}
class CreditCardPaymentStrategy implements PaymentStrategy {
public function calculateTotal($order) {
return $order->getTotal() + 0.03 * $order->getTotal(); // 应用 3% 费用
}
}
// 创建一个订单和选择一种支付策略
$order = new Order();
$order->setTotal(100);
$strategy = new CreditCardPaymentStrategy();
// 使用策略计算总额
$total = $strategy->calculateTotal($order); // 输出:103以上就是PHP 函数设计模式应用案例分析的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号