Comparison of decorator modes of PHP, Python, and Javascript

Source: Internet
Author: User
This article mainly introduces the comparison of DecoratorPattern in PHP, Python, and Javascript, also called DecoratorPattern, in the field of object-oriented programming, A dynamic addition to a class

This article mainly introduces the comparison of Decorator Pattern in PHP, Python, and Javascript, also called Decorator Pattern, in the field of object-oriented programming, A dynamic addition to a class

Decorator Pattern, also known as the modifier Pattern, is a design Pattern that dynamically adds new behaviors to a class in the object-oriented programming field. In terms of functions, the modifier mode is more flexible than the subclass generation, so that you can add some functions to an object rather than the entire class. The decoration mode is very suitable for the function of flexibly expanding objects. The following is a UML diagram of the decoration mode:

For example, in a technical forum where users communicate via messages, since the Forum was originally an acquaintance, almost no review of the message content is required. The page for receiving the message can be as follows:

Class SaveMsg () {private $ msg; public function _ construct ($ msg) {$ this-> msg = $ msg;} public function _ store () {// save to database }}

Later, as the forum became more famous, some people sent links to the Forum, and they needed to filter messages containing links. The Forum was further developed and found that apart from developing junk links, there is still a lot of useless bumping, and there may be attacks and other abnormal posts later. Therefore, the management of Forum posts can be abstracted separately for management, when you need to expand the filtering rules, you can dynamically expand them.

// Base class abstract class Filter {abstract public function isForbid ();} // base Filter 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] ;}}// decorator, used to Expand functions abstract class FilterDecorator extends Filter {protected $ obj; public function _ construct (Filter $ obj) {$ this-> obj = $ obj;} // new Filter, determine whether to repeatedly post class repeat extends FilterDecorator {public function isForbid () {if ($ this-> obj-> isForbid () [0] === true) {// determine whether the url return $ this-> obj-> isForbid ();} else if ($ this-> obj-> content = "this is a test ") {// determine whether to repeatedly post a post. return [true, "Repeat Posts"] ;}else {return [false] ;}}$ test = new MsgFilter ("httpsfdjoafdsajof "); print_r ($ test-> isForbid (); // forbidden $ test2 = new repeat (new MsgFilter ("this is a test ")); print_r ($ test2-> isForbid (); // disabled


In python, abstract classes and methods do not exist, making implementation easier:

#! /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 have 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 the prototype. It takes a little effort to understand it:

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 ());

Because Javascript lacks the class feature, inheritance is a little tricky for it. The above code looks more like processing two functions. In python, there is a simpler way to add a decoration device. You can directly add a decoration device to the function through "@" to achieve the purpose of extended functions, such:

Def Decorator (F): def newF (age): print "You Are Calling", F. _ name _ F (age) return newF @ Decorator # Add Decoratordef showAge (age): print "hello, I am % d years old "% ageshowAge (10)

The purpose of the decoration mode is to solve the problem of dynamic expansion. The essence of the decoration mode is to flexibly process objects and understand the decoration mode. In addition to in-depth understanding of object-oriented programming, it can improve the Thinking Ability of programming.

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.