核心:物件不可變,任何修改都回傳新實例,避免共用參考導致副作用。
<?php
// ❌ 錯誤示範:可變物件導致共用參考
class BadDollar {
public float $amount;
public function add(BadDollar $d): void { $this->amount += $d->amount; }
}
// ✅ 值物件:不可變
final class Dollar {
public function __construct(private float $amount) {}
public function getAmount(): float { return $this->amount; }
public function add(Dollar $d): Dollar {
return new Dollar($this->amount + $d->amount); // 回傳新實例
}
}
// 使用
$salary = new Dollar(200);
$p1Wallet = $salary;
$p2Wallet = $salary;
$p1Wallet = $p1Wallet->add($salary); // 400
echo $p2Wallet->getAmount(); // 200 (未受影響)
echo $salary->getAmount(); // 200 (原物件不變)
?>
場景:同一行為(如計價)有多種演算法(會員等級折扣),執行時動態切換。
<?php
interface PriceStrategy {
public function calculate(float $price): float;
}
class NormalStrategy implements PriceStrategy {
public function calculate(float $price): float { return $price; }
}
class VipStrategy implements PriceStrategy {
public function calculate(float $price): float { return $price * 0.8; }
}
class PremiumStrategy implements PriceStrategy {
public function calculate(float $price): float { return $price * 0.7; }
}
class PriceContext {
public function __construct(private PriceStrategy $strategy) {}
public function calculate(float $price): float {
return $this->strategy->calculate($price);
}
}
// 客戶端
$ctx = new PriceContext(new VipStrategy());
echo $ctx->calculate(100); // 80
?>
場景:將請求封裝為物件,支援佇列、撤銷、記錄、參數化調用者。
<?php
interface Command { public function execute(): void; }
class LightOnCommand implements Command {
public function __construct(private Light $light) {}
public function execute(): void { $this->light->on(); }
}
class RemoteControl {
private Command $command;
public function setCommand(Command $cmd) { $this->command = $cmd; }
public function press(): void { $this->command->execute(); }
}
// 使用
$remote = new RemoteControl();
$remote->setCommand(new LightOnCommand($livingRoomLight));
$remote->press(); // 燈亮
?>
場景:一對多依賴,主題狀態變更自動通知所有觀察者(事件系統、訂閱通知)。
<?php
interface Observer { public function update(string $event): void; }
interface Subject {
public function attach(Observer $o): void;
public function detach(Observer $o): void;
public function notify(string $event): void;
}
class MessageSystem implements Subject {
private array $observers = [];
public function attach(Observer $o) { $this->observers[] = $o; }
public function detach(Observer $o) {
$this->observers = array_filter($this->observers, fn($x) => $x !== $o);
}
public function notify(string $event) {
foreach ($this->observers as $o) $o->update($event);
}
public function post(string $msg) { $this->notify($msg); }
}
class User implements Observer {
public function __construct(private string $name) {}
public function update(string $event) { echo "{$this->name} 收到: $event\n"; }
}
// 使用
$sys = new MessageSystem();
$sys->attach(new User('小明'));
$sys->attach(new User('小紅'));
$sys->post('系統維護通知');
// 小明 收到: 系統維護通知
// 小紅 收到: 系統維護通知
?>
| 模式 | 解決問題 | 關鍵詞 |
|---|---|---|
| 值物件 | 共用參考副作用 | 不可變、無副作用 |
| 策略 | 演算法家族動態切換 | 介面隔離、組合大於繼承 |
| 命令 | 請求與執行解耦、支援撤銷/佇列 | 封裝請求、調用者不依賴實作 |
| 觀察者 | 狀態變更自動通知多方 | 發布/訂閱、鬆耦合 |