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 开发必备。
