欢迎来到程序员中文网!

首页 Linux Mysql C++ Python PHP JavaScript 资源下载 动态 开源推荐
我要投稿 投诉建议

PHP 设计模式:工厂模式与策略模式实现

时间:2026年08月12日 05:38:48 浏览:0

PHP 设计模式:工厂模式与策略模式实现


设计模式让代码更灵活、可维护。


1. 工厂模式


interface Logger {
public function log(string $message): void;
}

class FileLogger implements Logger {
public function log(string $message): void {
file_put_contents('/tmp/app.log', $message . PHP_EOL, FILE_APPEND);
}
}

class LoggerFactory {
public static function create(string $type): Logger {
return match ($type) {
'file' => new FileLogger(),
'database' => new DatabaseLogger(),
default => throw new InvalidArgumentException('未知类型')
};
}
}
// 使用
$logger = LoggerFactory::create('file');
$logger->log('系统启动');

2. 策略模式


interface PaymentStrategy {
public function pay(float $amount): bool;
}

class AlipayStrategy implements PaymentStrategy {
public function pay(float $amount): bool {
echo "使用支付宝支付 {$amount} 元";
return true;
}
}

class PaymentContext {
private PaymentStrategy $strategy;
public function setStrategy(PaymentStrategy $strategy): void {
$this->strategy = $strategy;
}
public function executePay(float $amount): bool {
return $this->strategy->pay($amount);
}
}

// 使用
$context = new PaymentContext();
$context->setStrategy(new AlipayStrategy());
$context->executePay(99.99);

设计模式是高级 PHP 开发必备。