PHP, Python, and JavaScript decorator pattern comparison, pythonjavascript_php tutorial

Source: Internet
Author: User

Comparison of adorner patterns in PHP, Python, and JavaScript, Pythonjavascript


The modified pattern (Decorator pattern), also known as decorator Mode, is a design pattern that dynamically adds new behavior to a class in the field of object-oriented programming. In terms of functionality, the grooming pattern is more flexible than generating subclasses, which can add functionality to an object rather than to the entire class. Decorative mode is ideal for flexible extended object functions, and the following is a UML diagram of decorative modes:

For example, there is a technical forum, the user through the message to communicate, since the beginning of the forum are acquaintances, almost do not need to comment on the content of the message to be reviewed, the page can be received message:

Class Savemsg () {private $msg; public function __construct ($msg) {$this->msg= $msg;} public Function __store () {//Deposit to database }}

Later, as the forum became famous, there are some people on the above to send a link, you need to filter the message containing the link, the Forum further development, found in addition to the development of garbage links, there are a lot of useless irrigation, and then there may be attacks and other abnormal posts, so the management of forum posts, A class can be abstracted separately for management, and can be dynamically augmented when it is necessary to expand the filtering rules.

Base class abstract class filter{abstract public Function isforbid ();} Basic Filter Class Msgfilter extends filter{public $content, Public function __construct ($msg) {$this->content= $msg;} publ IC function Isforbid () {if (Preg_match ("/https?/i", $this->content)) {return [true, ' not allowed Urls '];} else{return [FALSE];}} Adorner, used to augment the function abstract class Filterdecorator extends filter{protected $obj; public function __construct (Filter $obj) {$thi S->obj= $obj; }}//new filter, determine whether to repeat the Post class repeat extends filterdecorator{public function isforbid () {if ($this->obj->isforbid () [0] = = = True) {//Determines whether to include the URL return $this->obj->isforbid ();} else if ($this->obj->content = = "This is a test") {//Determines whether to repeat the post return [true, "Repeat Posts"];} else{return [FALSE];}} $test = new Msgfilter ("Httpsfdjoafdsajof");p Rint_r ($test->isforbid ()),//Forbidden $test2 = new repeat ("this is a Test "));p Rint_r ($test 2->isforbid ());//Is forbidden


In Python, there are no abstract classes and methods, and the implementation is simpler:

#!/usr/bin/env pythonclass Filter ():  passclass 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=objclass 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 with HTTP URLs") print test.isforbid () test2 = Repeat (msgfilter (' This is a test ') Print Test2.isforbid ()

In JavaScript, there are no strict classes, and all inheritance is based on prototypes, which can be a bit more understandable:

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 ("He is a content with HTTP URLs"), Console.log (Test.isforbid ()), var test2 = new Repeat (New Msgfil ter ("This is a Test"); Console.log (Test2.isforbid ());

Because JavaScript lacks the nature of the class, the inheritance for it is a bit of a chicken, the above code looks more like the processing of two functions, in Python, there is a more simple method of adding adorners, directly through the "@" to the function automatically add adorners, to achieve the purpose of extending the function, such as:

Def Decorator (f):  def NEWF (age):    print "is calling", f.__name__    F (age)  return newf@decorator# Add adorner to function Showage by @ decoratordef Showage (age):  print "Hello, I am%d years old"%ageshowage (10)

The purpose of decoration mode is to solve the problem of dynamic expansion function, the essence of decoration mode is to deal with the object flexibly, understand the decoration mode, not only can deeply understand object-oriented programming, but also can improve the thinking ability of programming.

http://www.bkjia.com/PHPjc/953154.html www.bkjia.com true http://www.bkjia.com/PHPjc/953154.html techarticle PHP, Python and JavaScript decorator pattern contrast, Pythonjavascript modified mode (Decorator pattern), also known as decorator mode, is the field of object-oriented programming, a dynamic to a ...

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.