工厂模式
工厂模式将对象的创建逻辑封装起来。
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 DatabaseLogger implements Logger {
public function log(string $message): void {
// 写入数据库
}
}
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('系统启动');策略模式
策略模式定义一系列算法,并可互换。
interface PaymentStrategy {
public function pay(float $amount): bool;
}
class AlipayStrategy implements PaymentStrategy {
public function pay(float $amount): bool {
echo "使用支付宝支付 {$amount} 元";
return true;
}
}
class WechatPayStrategy 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 开发者的必备技能。
