I can\'t seem to get my head around what advantages the strategy pattern offer. See the example below.
//Implementation without the strategy pattern
class Regist
Often, examples are somewhat odd, describing ducks, cats or else. Here is an example of Strategy Pattern used in displaying alerts. (Extending the Gordon's answer).
1. Interface for the methods, that vary (i.e., alert format in the case):
require_once("initialize/initialize.php");
interface alert{
public function alert($message);
};
2. Methods, that implement alert interface.
class alertBorderBullet implements alert{
public function alert($message){
$alert = "".$message."
";
return $alert;
}
};
class alertOrangeBgnd implements alert{
public function alert($message){
$alert = "".$message."
";
return $alert;
}
};
class alertRed implements alert{
public function alert($message){
$alert = "".$message."
";
return $alert;
}
};
3. Messenger, to separate alert method setting and getting from other objects in a project.
class alertMessenger{
protected $_alert;
public function setAlertType(alert $alert){$this->_alert = $alert;}
public function returnAlert($message){return $this->_alert->alert($message);}
};
4. A random project object that will use "alerting" in different ways.
class randomObject{
public $alert;
public function __construct(){
$this->alert = new alertMessenger;
}
// More code here...
};
$randomObject = new randomObject;
$randomObject->alert->setAlertType(new alertRed);
echo $randomObject->alert->returnAlert($message="Red text for critical info");
$randomObject->alert->setAlertType(new alertBorderBullet);
echo $randomObject->alert->returnAlert($message="Border, bullet and pale-color text");
echo $randomObject->alert->returnAlert($message="Repeat, check style permanence");
$randomObject->alert->setAlertType(new alertOrangeBgnd);
echo $randomObject->alert->returnAlert($message="Again, another redefined message style");
randomObject, when initialized (for this case) automatically creates an instance of alertMessanger and makes its methods available. Behaviors can be set and messages echoed. Other alert formats can be created and used when necessary by setAlertType and then returnAlert.