Skip to content

设计模式

MineShop 中使用的主要设计模式和实现方式。

🎯 模式概览

模式应用场景示例
Repository数据访问抽象OrderRepository
Factory对象创建EntityFactory
Strategy算法切换PaymentStrategy
Observer事件通知OrderPaidEvent
Decorator功能增强CacheDecorator

📦 Repository 模式

抽象数据访问,隔离领域层与数据库。

php
// 接口定义
interface OrderRepositoryInterface
{
    public function findById(int $id): ?OrderEntity;
    public function save(OrderEntity $entity): Order;
}

// 实现
class OrderRepository implements OrderRepositoryInterface
{
    public function findById(int $id): ?OrderEntity
    {
        $model = Order::find($id);
        return $model ? OrderMapper::fromModel($model) : null;
    }
    
    public function save(OrderEntity $entity): Order
    {
        return Order::create($entity->toArray());
    }
}

🏭 Factory 模式

封装复杂对象的创建逻辑。

php
// Mapper 作为工厂
class OrderMapper
{
    public static function fromDto(CreateOrderDto $dto): OrderEntity
    {
        return new OrderEntity(
            memberId: $dto->memberId,
            items: array_map(
                fn($item) => OrderItemMapper::fromDto($item),
                $dto->items
            ),
            address: AddressMapper::fromDto($dto->address),
        );
    }
    
    public static function fromModel(Order $model): OrderEntity
    {
        return new OrderEntity(
            id: $model->id,
            orderNo: $model->order_no,
            status: OrderStatus::from($model->status),
        );
    }
}

🎯 Strategy 模式

支持多种支付方式的灵活切换。

php
// 策略接口
interface PaymentStrategyInterface
{
    public function pay(Order $order): PaymentResult;
    public function refund(Order $order, float $amount): RefundResult;
}

// 微信支付策略
class WechatPaymentStrategy implements PaymentStrategyInterface
{
    public function pay(Order $order): PaymentResult
    {
        // 微信支付实现
    }
}

// 余额支付策略
class BalancePaymentStrategy implements PaymentStrategyInterface
{
    public function pay(Order $order): PaymentResult
    {
        // 余额支付实现
    }
}

// 上下文
class PaymentContext
{
    public function process(Order $order, string $method): PaymentResult
    {
        $strategy = match($method) {
            'wechat' => new WechatPaymentStrategy(),
            'balance' => new BalancePaymentStrategy(),
            default => throw new \InvalidArgumentException('不支持的支付方式'),
        };
        
        return $strategy->pay($order);
    }
}

👀 Observer 模式

通过事件实现模块解耦。

php
// 定义事件
class OrderPaidEvent
{
    public function __construct(
        public readonly Order $order,
        public readonly array $paymentData,
    ) {}
}

// 监听器
#[Listener]
class SendOrderPaidNotification implements ListenerInterface
{
    public function listen(): array
    {
        return [OrderPaidEvent::class];
    }
    
    public function process(object $event): void
    {
        // 发送支付成功通知
        $this->notificationService->send($event->order);
    }
}

// 触发事件
event(new OrderPaidEvent($order, $paymentData));

🎨 Decorator 模式

为服务添加缓存能力。

php
// 原始服务
class ProductService
{
    public function getDetail(int $id): ?Product
    {
        return Product::find($id);
    }
}

// 缓存装饰器
class CachedProductService
{
    public function __construct(
        private ProductService $service,
        private CacheInterface $cache,
    ) {}
    
    public function getDetail(int $id): ?Product
    {
        $key = "product:{$id}";
        
        return $this->cache->remember($key, 3600, function() use ($id) {
            return $this->service->getDetail($id);
        });
    }
}

✅ 使用建议

  1. 不要过度设计: 简单场景不需要复杂模式
  2. 优先组合: 组合优于继承
  3. 接口隔离: 依赖抽象而非具体实现
  4. 单一职责: 每个类只做一件事

📚 相关文档

基于 Apache-2.0 许可发布 | 感谢 MineAdmin 提供的优秀基础框架