装饰器模式概述与论坛场景
装饰者模式(Decorator Pattern)属于面向对象编程范畴,旨在动态地为某个类注入新行为。在功能扩展方面,该模式比创建子类更具灵活性,允许针对特定对象而非整个类进行功能增强。这种机制特别适合需要灵活扩展对象功能的场景,其结构可参考下方的UML图:

以技术论坛为例,初期用户间交流无需审核留言内容,接收页面的实现较为简单:
class SaveMsg(){
private $msg;
public function __construct($msg){
$this->msg=$msg;
}
public function __store(){
//存入数据库
}
}
随着论坛知名度提升,出现发布链接的情况,需对含链接的消息进行过滤。后续又面临灌水、攻击等异常帖子问题,因此可将帖子管理抽象为独立类以便动态扩充过滤规则。
//基类
abstract class Filter{
abstract public function isForbid();
}
//基础过滤类
class MsgFilter extends Filter{
public $content;
public function __construct($msg){
$this->content=$msg;
}
public function isForbid(){
if(preg_match("/https?/i",$this->content)){
return [true,"Not Allowed Urls"];
}else{
return [false];
}
}
}
//装饰器,用来扩充功能
abstract class FilterDecorator extends Filter{
protected $obj;
public function __construct(Filter $obj){
$this->obj=$obj;
}
}
//新过滤器,判断是否重复发帖
class repeat extends FilterDecorator{
public function isForbid(){
if($this->obj->isForbid()[0] === true){
//判定是否包含url
return $this->obj->isForbid();
}else if($this->obj->content == "this is a test"){
//判定是否重复发帖
return [true,"Repeat Posts"];
}else{
return [false];
}
}
}
$test = new MsgFilter("httpsfdjoafdsajof");
print_r($test->isForbid());//被禁止
$test2 = new repeat(new MsgFilter("this is a test"));
print_r($test2->isForbid());//被禁止
在Python中,由于缺乏严格的抽象类与方法概念,实现过程相对简便:
#!/usr/bin/env python
class Filter():
pass
class MsgFilter(Filter):
def __init__(self,msg):
self.content=msg
def isForbid(self):
if('http' in self.content):
return [True,"Not Allowed Urls"]
else:
return [False]
class FilterDecorator(Filter):
def __init__(self,obj):
self._obj=obj
class Repeat(FilterDecorator):
def isForbid(self):
if self._obj.isForbid()[0]:
return self._obj.isForbid()
elif self._obj.content == 'this is a test':
return [True,"Repeat Posts"];
else:
return [False]
test = MsgFilter("this is a content have http urls")
print test.isForbid()
test2 = Repeat(MsgFilter('this is a test'))
print test2.isForbid()
JavaScript没有严格的类定义,所有继承均基于原型链,理解起来稍显复杂:
function MsgFilter(msg){
this.content=msg;
this.isForbid=function(){
if(this.content.match(/http/g)){
return [true,"Not Allowed Urls"];
}else {
return [false];
}
}
}
function Repeat(obj){
var _obj=obj;
this.isForbid=function(){
if(_obj.isForbid[0] === true){
return _obj.isForbid();
}else if(_obj.content=='this is a test'){
return [true,"Repeat Posts"];
}else{
return [false];
}
}
}
var test = new MsgFilter("his is a content have http urls");
console.log(test.isForbid());
var test2 = new Repeat(new MsgFilter("this is a test"));
console.log(test2.isForbid());
因JavaScript缺少传统类的特性,其继承机制显得略为鸡肋,上述代码更像是对两个函数的处理。而在Python中,有更简洁的方式添加装饰器,即直接使用“@”符号自动为函数附加装饰器以实现功能扩展,例如:
def Decorator(F):
def newF(age):
print "You Are Calling",F.__name__
F(age)
return newF
@Decorator
#通过@给函数showAge添加装饰器Decorator
def showAge(age):
print "hello , i am %d years old"%age
showAge(10)
装饰模式的核心目标是解决动态扩展功能的难题,其本质在于对对象的灵活处理。深入理解此模式不仅有助于掌握面向对象程序设计,还能提升编程思维水平。