设计模式是 php 中用于创建可维护、可扩展且可重用的代码的经过验证的解决方案。基本设计模式可分为创建型、结构型和行为型。实战案例展示了设计模式在购物车系统中的应用,包括使用工厂模式创建折扣服务对象,使用代理模式为购物车添加日志功能,以及通过策略模式实现各种折扣计算。

PHP 设计模式:从入门到精通
引言
设计模式是经过验证的代码解决方案,可用于解决常见编程问题。在 PHP 中,设计模式可以帮助我们编写可维护、可扩展且可重用的代码。
立即学习“PHP免费学习笔记(深入)”;
基本设计模式
创建型模式:提供创建对象的机制。
结构型模式:定义类和对象之间的关系。
行为型模式:定义对象如何通信和协作。
实战案例:购物车
考虑一个购物车系统,其中包含以下类:
Cart:表示购物车,存储购买的物品。Item:表示购物车中的单个物品。DiscountService:提供计算折扣的接口。使用工厂模式创建 DiscountService 对象:
interface DiscountServiceFactory {
public static function create(): DiscountService;
}
class NormalDiscountService implements DiscountService {
// ...
}
class PremiumDiscountService implements DiscountService {
// ...
}
class DiscountServiceFactoryImpl implements DiscountServiceFactory {
public static function create(): DiscountService {
if (isPremiumCustomer()) {
return new PremiumDiscountService();
}
return new NormalDiscountService();
}
}使用代理模式为 Cart 添加日志功能:
class CartLoggerProxy extends Cart {
private $logger;
public function __construct(Cart $cart, Logger $logger) {
parent::__construct();
$this->cart = $cart;
$this->logger = $logger;
}
public function addItem(Item $item): void {
parent::addItem($item);
$this->logger->log("Added item to cart");
}
// 其他方法类似处理
}通过策略模式实现各种折扣计算:
interface DiscountStrategy {
public function calculateDiscount(Cart $cart): float;
}
class NoDiscountStrategy implements DiscountStrategy {
public function calculateDiscount(Cart $cart): float {
return 0;
}
}
class FlatDiscountStrategy implements DiscountStrategy {
private $discount;
public function __construct(float $discount) {
$this->discount = $discount;
}
public function calculateDiscount(Cart $cart): float {
return $cart->getTotal() * $this->discount;
}
}
// ... 更多策略
$context = new DiscountContext();
if (isPremiumCustomer()) {
$context->setStrategy(new PremiumDiscountStrategy());
} else {
$context->setStrategy(new NoDiscountStrategy());
}
$discount = $context->calculateDiscount();结论
通过使用设计模式,我们可以创建优雅、灵活和可维护的 PHP 代码。在本文中介绍的基本设计模式可以帮助我们解决广泛的编程挑战,并构建高质量的软件。
以上就是PHP 设计模式从入门到精通的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号