In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces the relevant knowledge of "how to realize duck type and polymorphism in javascript design pattern". The editor shows you the operation process through an actual case. The operation method is simple, fast and practical. I hope this article "how to realize duck type and polymorphism in javascript design pattern" can help you solve the problem.
1. Duck type
The popular saying for the duck type is: "if it walks like a duck and barks like a duck, then it is a duck."
Professional explanation of duck type: for example, in a language that does not use duck type, we can write a function that accepts an object of type "duck" and calls its "walk" and "call" methods, but it can only accept objects of duck type, otherwise report an error. In a language that uses the duck type, such a function can accept an object of any type and call its "go" and "call" methods. If these methods that need to be called do not exist, a run-time error is raised. Any object with such correct "go" and "call" methods can be called by the function, which is consistent with the duck type.
So if a weakly typed language (js) function needs to receive parameters, in order to ensure robustness, you should first determine the type of parameters and determine whether the parameters contain methods and attributes that need to be accessed. Only when these conditions are met will the program really deal with the methods and parameters of the calling parameters.
Var duck = {sing: function () {console.log ('function');}} var chicken = {sing: function () {console.log ('Gaga') }} var choir = [] / / choir function joinChoir (duck) {if (duck & & typeof duck.sing = 'function') {choir.push (duck) console.log (' choir added a member') }} joinChoir (duck) joinChoir (chicken) / / chorus for (let I = 0; I < choir +) {choir [I] .sing ()} 2. Polymorphism 2.1 java polymorphism
For object-oriented, polymorphism is divided into compile-time polymorphism and run-time polymorphism. Among them, compile-time polymorphism is static, which mainly refers to the overloading of methods, which distinguishes different methods according to different parameter lists. After compilation, it becomes two different methods, which are not polymorphic at run time. Run-time polymorphism is dynamic, which is realized by dynamic binding, which is commonly referred to as polymorphism.
In java, polymorphism is the ability of the same behavior to have different forms or forms, that is, the embodiment of multiple forms of expression of an object, that is, the specific type pointed to by the reference variable defined in the program and the method calls made through the reference variable are not determined during programming, but are determined during the running of the program, that is, the instance object of which class a reference variable will point to. The method call made by the reference variable is implemented in which class, which must be determined during the run of the program. To put it simply, the compile-time object is the parent class type, and it is not until the actual run time that the object knows which subclass type it is and the method implemented in which subclass to call.
There are three necessary conditions for Java to achieve polymorphism: inheritance, rewriting, and upward transformation. Only when these three conditions are met will developers be able to use unified logic implementation code to deal with different objects in the same inheritance structure, thus performing different behaviors.
Inheritance: there must be subclasses and parents with inherited relationships in polymorphisms.
Override: the subclass redefines some methods in the parent class, and when these methods are called, the methods of the subclass are called.
Upward transformation: in polymorphism, you need to assign a reference to the subclass to the parent object, so that the reference can call both the method of the parent class and the method of the subclass.
From this, we can get the benefits of using polymorphism, we can decouple and work the code very well, strengthen the expansibility of the code, make the code more flexible, simplify the process without changing the original interface method, etc., to sum up:
Decoupling
Enhanced replaceability
Expandability
Flexibility, etc.
As an example of life, as shown in the following figure: when scanning a QR code for payment using a mobile phone, the QR code does not know how the customer makes the payment, and only through the QR code can we determine which payment method to use to implement the corresponding process.
As a code example, create the Figure class, which first defines the size of the stored two-dimensional object, then defines a construction method with two parameters, and finally adds the area () method, which calculates the area of the object. The code is as follows:
Public class Figure {double dim1; double dim2; Figure (double D1, double D2) {/ / the construction method with parameters this.dim1 = D1; this.dim2 = D2;} double area () {/ / is used to calculate the area System.out.println of the object ("the method of calculating the area of the object in the parent class is of no practical significance and needs to be rewritten in the subclass.") ; return 0;}}
Create a Rectangle subclass that inherits from the Figure class, which calls the constructor of the parent class and overrides the area () method in the parent class. The code is as follows:
Public class Figure {double dim1; double dim2; Figure (double D1, double D2) {/ / the construction method with parameters this.dim1 = D1; this.dim2 = D2;} double area () {/ / is used to calculate the area System.out.println of the object ("the method of calculating the area of the object in the parent class is of no practical significance and needs to be rewritten in the subclass.") ; return 0;}}
Create a Triangle subclass that inherits from the Figure class, which is similar to Rectangle. The code is as follows:
Public class Rectangle extends Figure {Rectangle (double D1, double D2) {super (D1, D2);} double area () {System.out.println ("rectangular area:"); return super.dim1 * super.dim2;}}
Create a Test test class, first declare the variable figure of the Figure class in its main () method, then specify different objects for the figure variable, and call the area () method of those objects. The code is as follows:
Public class Rectangle extends Figure {Rectangle (double D1, double D2) {super (D1, D2);} double area () {System.out.println ("rectangular area:"); return super.dim1 * super.dim2;}}
As you can see from the above code, regardless of whether the object of the figure variable is Rectangle or Triangle, they are subclasses of the Figure class, so they can be transformed up to this class to achieve polymorphism.
2.2 js polymorphism
The actual meaning of polymorphism is that the same operation acts on different objects and can produce different interpretations and different execution results. In other words, when sending the same message to different objects, the objects will give different feedback based on the message.
Let's give an example of what polymorphism actually means:
There are two animals in the owner's house, a duck and a chicken. When the owner gives them an order to "bark", the duck will "quack" and the chicken will "cackle". Both animals make calls in their own way. They are also "all animals and can make calls", but according to their owners' instructions, they will make different calls.
Var Duck = function () {} Duck.prototype.sing = function () {console.log (Gaga);} var Chicken = function () {} Chicken.prototype.sing = function () {console.log (Gaga) } function sing (animal) {if (animal & & (typeof animal.sing = 'function')) {animal.sing ()}} sing (new Duck ()) sing (new Chicken ())
The idea behind polymorphism is to separate "what to do" from "who does it and how to do it", that is, to separate "immutable things" from "things that may change". In this story, all animals will bark, which is the same, but the exact name of different types of animals is variable. Isolating the immutable parts and encapsulating the variable parts gives us the ability to extend the program, which appears to be growable and conforms to the open-closed principle, as opposed to modifying the code. it is obviously much more elegant and secure to simply add code to accomplish the same function.
The realization of polymorphism: the idea of polymorphism is actually to separate "what to do" from "who will do it". To achieve this, in the final analysis, it is necessary to eliminate the coupling between types. If the coupling between types is not eliminated, then we specify in the makeSound method that the object making the call is of one type, and it cannot be replaced with another type. In Java, polymorphism can be achieved through upward transformation. The variable type of JavaScript is variable at run time. A JavaScript object can represent both Duck and Chicken objects, which means that JavaScript objects are inherently polymorphic. This innate polymorphism is not difficult to explain. As a dynamically typed language, JavaScript has no process of type checking at compile time, neither checking the created object types nor checking the passed parameter types.
The most fundamental benefit of polymorphism: you no longer have to ask the object "what type are you" and then call a behavior of the object based on the answer you get-just call that behavior, and all other polymorphic mechanisms will be arranged for you. In other words, the most fundamental function of polymorphism is to eliminate these conditional branching statements by transforming procedural conditional branching statements into object polymorphism.
The most fundamental benefits of polymorphism can be well illustrated by the following example: on the set of the film, when the director shouted "action", the protagonist began to recite the lines, the illuminator turned on the lights, the extras pretended to be shot to the ground, and the prop master sprinkled snowflakes into the camera. When you get the same message, each object knows what to do. If you write this code in a process-oriented way instead of taking advantage of the polymorphism of the object, then the director has to go to everyone every time after the film starts filming to confirm their professional division of labor (type). And tell them what to do. If you map to a program, the program will be full of conditional branch statements. Taking advantage of the polymorphism of the object, the director does not have to consider what each object should do after receiving the message when publishing the message. What the object should do is not decided temporarily, but has been agreed upon and rehearsed in advance. What each object should do has become a method of the object, installed inside the object, and each object is responsible for its own behavior. So these objects can do their own work methodically according to the same message.
It is the advantage of object-oriented design to distribute behaviors among objects and make these objects responsible for their own behavior.
That's all for "how to implement duck types and polymorphisms in javascript design patterns". Thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.