php design mode Decorator of decoration mode

  • 2020-05-09 18:15:31
  • OfStack

 
<?php 
/** 
*  Decorative pattern  
* 
*  Dynamic to 1 Object add 1 Some extra responsibilities , More flexibility in extending functionality than in subclassing  
*/ 
header("Content-type:text/html;charset=utf-8"); 
abstract class MessageBoardHandler 
{ 
public function __construct(){} 
abstract public function filter($msg); 
} 

class MessageBoard extends MessageBoardHandler 
{ 
public function filter($msg) 
{ 
return " Deal with the message board |".$msg; 
} 
} 

$obj = new MessageBoard(); 
echo $obj->filter("1 Must learn adornment pattern well <br/>"); 

// ---  The following is the use of decorative patterns  ---- 
class MessageBoardDecorator extends MessageBoardHandler 
{ 
private $_handler = null; 

public function __construct($handler) 
{ 
parent::__construct(); 
$this->_handler = $handler; 
} 

public function filter($msg) 
{ 
return $this->_handler->filter($msg); 
} 
} 

//  filter html 
class HtmlFilter extends MessageBoardDecorator 
{ 
public function __construct($handler) 
{ 
parent::__construct($handler); 
} 

public function filter($msg) 
{ 
return " To filter out HTML The label |".parent::filter($msg);; //  To filter out HTML Label handling   It's just a text   Not processed  
} 
} 

//  Filter sensitive word  
class SensitiveFilter extends MessageBoardDecorator 
{ 
public function __construct($handler) 
{ 
parent::__construct($handler); 
} 

public function filter($msg) 
{ 
return " Filter out sensitive words |".parent::filter($msg); //  Filter out the processing of sensitive words   It's just a text   Not processed  
} 
} 

$obj = new HtmlFilter(new SensitiveFilter(new MessageBoard())); 
echo $obj->filter("1 Must learn adornment pattern well !<br/>"); 

Related articles: