Design Pattern :: Strategy Pattern
- sukorn's blog
- 28 comments
- Read more
- 606 reads
Strategy Pattern เป็น design pattern ที่เอาไว้ใช้ตอนที่เราต้องเลือกทำสิ่งหนึ่ง แต่วิธีการหลากหลายออกไป เช่น เราจะสร้างระบบแจ้งเตือน user ซึ่งสามารถเตือนได้ทั้งแบบ e-mail sms และ fax pattern นี้ต้องการ interface ตัวนึง เราให้ชื่อว่า notifier คลาสที่ implements ก็จะมี EmailNotifier, SMSNotifier และ FaxNotifier ซึ่งเป็นวิธีการแจ้งเตือน user นั่นเอง โค้ด
<?php class User { private $name; protected $notifier; public function __construct($name) { $this->name = $name; } public function setNotifier(INotifier $notifier) { $this->notifier = $notifier; } public function notify() { $this->notifier->notify(); } } interface INotifier { public function notify(); } class EmailNotifier implements INotifier { public function notify() { echo "Notify by Email"; } } class SMSNotifier implements INotifier { public function notify() { echo "Notify by SMS"; } } class FaxNotifier implements INotifier { public function notify() { echo "Notify by Fax"; } } $john = new User('John'); $smith = new User('Smith'); $edward = new User('Edward'); $john->setNotifier(new EmailNotifier()); $smith->setNotifier(new SMSNotifier()); $edward->setNotifier(new FaxNotifier()); $john->notify(); $smith->notify(); $edward->notify();