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();
 
 
?>
จากโค้ดข้างบนจะเห็นว่าเราจะทำการแจ้งเตือน user ด้วยค่าที่ user เก็บไว้ (ในที่นี้คือ sms) ไม่ว่าจะเลือกเป็นอะไร notifier จะเรียก method notify() แค่ชื่อเดียว ซึ่งเป็นการใช้ประโยชน์จาก interface และหากมีระบบแจ้งเตือนแบบใหม่เราก็เพิ่มเข้าไปได้ง่ายตาม pattern

อ้างอิง: http://www.oodesign.com/strategy-pattern.html