複製程式碼 程式碼如下:
/**
* 裝飾模式
*
* 動態的給一個物件添加一些額外的職責,就擴展功能而言比生成子類方式更為靈活
*/
header("Content-type:text/html;charset=utf-8");
abstract class MessageBoardHandler ){}
abstract public function filter($msg);
}
class MessageBoard extends MessageBoardHandler
{
public function filter($msg);
}
$obj = new MessageBoard();
echo $obj->filter("一定要學好裝飾模式
");
// --- 以下是使用裝飾模式----
class MessageBoardDecorator extends MessageBoardHandler
{
private $_handler = null;
public function __construct($handler) 我
public function filter( $msg)
{
return $this->_handler->filter($msg);
}
}
// 過濾html
class HtmlFilter extends MessageBoardDecorator
parent: :__construct($handler);
}
public function filter($msg)
{
return "過濾掉HTML標籤|".parent::filter($msg);; // 過濾掉HTML標籤的處理這時HTML標籤的處理此時只是加個文字沒有進行處理
}
}
// 過濾敏感詞
class SensitiveFilter extends MessageBoardDecorator
{
public f215%($ler)($ler);
public function filter($msg)
{
return "過濾掉敏感字|".parent::filter($msg); // 過濾掉敏感字的處理這時只是加個文字沒有進行處理
}
}
$obj = new HtmlFilter(new SensitiveFilter(new MessageBoard()));
echo $obj->filter("一定要學好裝飾模式!
");