


Detailed explanation of the usage of Javascript's decorator mode compared with php and python
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.
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 it was necessary to filter messages containing links. The forum further developed and found that in addition to developing In addition to spam links, there are also a lot of useless spamming, and later there may be attacks and other abnormal posts. Therefore, for the management of forum posts, a separate class can be abstracted for management. When the filtering rules need to be expanded, 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 is no strict class, all inheritance is based on prototype, it will take 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 difficult for it. It's useless. The above code looks more like the processing of two functions. In python, there is a simpler way to add decorators. You can directly add decorators to functions directly through "@" to achieve the purpose of extending functions. For example:
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 provide an in-depth understanding of the oriented Object programming can improve programming thinking skills.
The above is the detailed content of Detailed explanation of the usage of Javascript's decorator mode compared with php and python. For more information, please follow other related articles on the PHP Chinese website!

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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

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











PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".
