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(); ?>
อ้างอิง: http://www.oodesign.com/strategy-pattern.html
- sukorn's blog
- Login to post comments
- 876 reads
อืมม์ ...
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
เซือในสิ่งที่เฮ็ด เฮ็ดในสิ่งที่เซือ...
-------------
En Taro Adun!