多くの場合、例はやや奇妙で、アヒル、猫などを表しています。アラートの表示に使用される戦略パターンの例を次に示します。(ゴードンの答えを拡張する)。
1. さまざまなメソッドのインターフェース (つまり、この場合のアラート形式):
require_once("initialize/initialize.php");
interface alert{
public function alert($message);
};
2. アラート インターフェイスを実装するメソッド。
class alertBorderBullet implements alert{
public function alert($message){
$alert = "<p style='border:1px solid #eee; padding:4px; padding-left:8px; padding-right:8px; border-left:4px solid #FC0; margin-top:8px; margin-bottom:8px; color:#888'>".$message."</p>";
return $alert;
}
};
class alertOrangeBgnd implements alert{
public function alert($message){
$alert = "<p style='color:#fff; background-color:#ff9c3a; padding:4px; padding-left:8px; padding-right:8px; margin-top:8px; margin-bottom:8px; border-left:4px solid #e471bd;'>".$message."</p>";
return $alert;
}
};
class alertRed implements alert{
public function alert($message){
$alert = "<p style='color:#c11; background-color:#efefef; padding:4px; padding-left:12px; padding-right:8px; margin-top:8px; margin-bottom:8px;'>".$message."</p>";
return $alert;
}
};
3. メッセンジャー。アラート メソッドの設定と、プロジェクト内の他のオブジェクトからの取得を分離します。
class alertMessenger{
protected $_alert;
public function setAlertType(alert $alert){$this->_alert = $alert;}
public function returnAlert($message){return $this->_alert->alert($message);}
};
4. さまざまな方法で「アラート」を使用するランダム プロジェクト オブジェクト。
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 は、初期化されると (この場合)、自動的に alertMessanger のインスタンスを作成し、そのメソッドを使用可能にします。動作を設定して、メッセージをエコーすることができます。setAlertType と returnAlert によって、必要に応じて他のアラート形式を作成して使用できます。