PHP 設計模式之工廠模式
阿新 • • 發佈:2020-12-28
工廠模式
interface Message { public function send(string $msg); } class AliYunMessage implements Message { public function send(string $msg) { return '阿里雲簡訊(原阿里大魚)傳送成功!簡訊內容:' . $msg; } } class BaiduYunMessage implements Message { public function send(string $msg) { return '百度SMS簡訊傳送成功!簡訊內容:' . $msg; } } abstract class MessageFactory { abstract protected function factoryMethod(); public function getMessage() { return $this->factoryMethod(); } } class AliYunFactory extends MessageFactory { protected function factoryMethod(){ return new AliYunMessage(); } } class BaiduYunFactory extends MessageFactory { protected function factoryMethod(){ return new BaiduYunMessage(); } } // 使用百度 $factory = new BaiduYunFactory(); $message = $factory->getMessage(); echo $message->send('您有新的短訊息,請查收');