


Comparison of decorator patterns in PHP, Python and Javascript, pythonjavascript_PHP tutorial
Comparison of decorator patterns in PHP, Python and Javascript, pythonjavascript
Decorator Pattern, also called Decorator Pattern, is a design pattern in the field of object-oriented programming that dynamically adds new behaviors to a class. In terms of functionality, the modification pattern is more flexible than subclassing, allowing you to add some functionality to an object rather than to the entire class. The decoration pattern is very suitable for flexibly extending the functionality of objects. The following is the UML diagram of the decoration pattern:
For example, there is a technical forum where users communicate through messages. Since the forum is full of acquaintances at the beginning, there is almost no need to review the content of the messages. The page for receiving messages can look like this:
class SaveMsg(){ private $msg; public function __construct($msg){ $this->msg=$msg; } public function __store(){ //存入数据库 } }
Later, as the forum became famous, some people posted links on it, and messages containing links needed to be filtered. As the forum developed further, it was discovered that in addition to those who developed spam links, there were also a lot of useless spammers. Later, there may be attacks and other abnormal posts, so for the management of forum posts, a separate class can be abstracted for management. When the filtering rules need to be expanded, they can be dynamically expanded.
//基类 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());//被禁止
In python, there are no abstract classes and methods, and the implementation is simpler:
#!/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()
In Javascript, there are no strict classes. All inheritance is based on prototypes, which takes a little effort to understand:
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());
Since Javascript lacks the characteristics of classes, inheritance is a bit useless for it. The above code looks more like the processing of two functions. In python, there is a simpler way to add decorators. Automatically add decorators to functions directly through "@" to extend functions, such as:
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)
The purpose of the decoration mode is to solve the problem of dynamic expansion of functions. The essence of the decoration mode is the flexible processing of objects. Understanding the decoration mode can not only have an in-depth understanding of object-oriented programming, but also improve programming thinking skills.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

The speed of mobile XML to PDF depends on the following factors: the complexity of XML structure. Mobile hardware configuration conversion method (library, algorithm) code quality optimization methods (select efficient libraries, optimize algorithms, cache data, and utilize multi-threading). Overall, there is no absolute answer and it needs to be optimized according to the specific situation.

An application that converts XML directly to PDF cannot be found because they are two fundamentally different formats. XML is used to store data, while PDF is used to display documents. To complete the transformation, you can use programming languages and libraries such as Python and ReportLab to parse XML data and generate PDF documents.

It is impossible to complete XML to PDF conversion directly on your phone with a single application. It is necessary to use cloud services, which can be achieved through two steps: 1. Convert XML to PDF in the cloud, 2. Access or download the converted PDF file on the mobile phone.

There is no built-in sum function in C language, so it needs to be written by yourself. Sum can be achieved by traversing the array and accumulating elements: Loop version: Sum is calculated using for loop and array length. Pointer version: Use pointers to point to array elements, and efficient summing is achieved through self-increment pointers. Dynamically allocate array version: Dynamically allocate arrays and manage memory yourself, ensuring that allocated memory is freed to prevent memory leaks.

XML can be converted to images by using an XSLT converter or image library. XSLT Converter: Use an XSLT processor and stylesheet to convert XML to images. Image Library: Use libraries such as PIL or ImageMagick to create images from XML data, such as drawing shapes and text.

Use most text editors to open XML files; if you need a more intuitive tree display, you can use an XML editor, such as Oxygen XML Editor or XMLSpy; if you process XML data in a program, you need to use a programming language (such as Python) and XML libraries (such as xml.etree.ElementTree) to parse.
