Proficient in javascript--05 design mode: Create type

Source: Internet
Author: User

Use the tips of design patterns to think of them as a variety of tools in your programming toolbox, each with a specific purpose. Before you try to apply design patterns to your code, you first need to familiarize yourself with the various existing design patterns and the situations where each is applied (using the wrong tool will result in unnecessary hassles and wasted time). These chapters will help you to achieve this. Unless you're a particularly sophisticated JavaScript developer, you don't have a specific design pattern in mind when you start writing code for your application. As your code continues to accumulate, you will find that you need to change your code to make future development easier to manage, and to manage the files in your code base in a certain structure and discipline. This process is often referred to as "refactoring." In general, it is at this stage of development to consider applying specific design patterns or architectural patterns to code to simplify the subsequent development effort. Be cautious with people who insist on keeping a particular design pattern in mind when the project starts, or using a particular pre-built JavaScript framework at the outset. The reason for this is that unless they are very experienced professionals, it is tantamount to choosing a completely new tool without experience before they can identify the tools needed to solve the problem.

You should be familiar with the design patterns and architectural patterns presented in each chapter, carefully learning each pattern and understanding how it is used. Over time, you will gradually recognize the specific patterns that your code needs to apply, improving the maintainability of your code and, in some cases, improving efficiency.

5.1 What is design mode

Design patterns are tried and tested by validation, by validating code writing and organizing methods. By providing a clear structure for developers to remove unnecessary complexity and decouple connections from different parts of a large code base, the code is easier to understand and easier to maintain. The various design patterns are like the tools in the programming toolbox.

Introduces 23 different design patterns, which can be divided into 3 categories: created, structured, and behavioral.

5.2 Creating design Patterns

The Create design pattern gives you a description of the class or method used to create the object without having to create the object yourself directly. This abstraction layer gives you and your code a greater degree of flexibility when deciding what type of object or object is most relevant to the particular situation and needs you are facing. Here, I will introduce you to 5 types of creation design patterns, each with a corresponding example. You'll find that these design patterns are very useful for your code.

5.21 Factory mode

With Factory mode, you can create objects without specifying a specific "class". In the previous chapters, when "class" was involved, we needed to create an instance of a particular class or subclass directly using the JavaScript keyword new. Using the factory model, the object creation process is abstracted so that the relatively complex object creation process can be encapsulated under a simple interface without the need for the new keyword. This abstraction means that the type and method used as the background "class" for creating each instance can be completely replaced at any time without altering the interface to accommodate the creation of the class. From the perspective of other developers, there is no need to change under the regular interface. Using Factory mode is ideal if you anticipate that many changes may be required in the future, but you do not want to have to rewrite the "class" instantiation code that walks in a large number of other code.

Code Listing 5-1 shows an example of a factory pattern. According to the different input parameters of the factory method, the object's instantiation is realized based on several different "classes".

Code Listing 5-1 Factory mode

1             //define a factory that uses the most appropriate "class" to create the appropriate form Field object for us based on what you have entered.2             varformfieldfactory={3                 //Makefield method Use 2 options4                 //-type, defines the type of form Field object created, such as text,email or button5                 //-displaytext, based on the type of the object, defines the placeholder (placeholder) text of the form field or the text displayed on the button6Makefield:function(options) {7                     varoptions=options | |{},8type=options.type| | " Text,9Displaytext=options.displaytext | | "",Ten field; One                     //use the most appropriate class to create an object instance based on the type provided A                     Switch(type) { -                          Case"Text": -Field=NewTextField (displayText); the                              Break; -                          Case"Email": -Field=NewEmailfield (displayText); -                              Break; +                          Case"Button": -Field=NewButtonField (displayText); +                              Break; A                         //If you are unsure, use the TextField "class" at                         default: -Field=NewTextField (displayText); -                              Break; -                     } -                     returnfield; -                      in                 } -             }; to             //define TextField "class" for creating <input type= "text" > table cells +             functionTextField (displayText) { -                  This. displaytext=DisplayText; the             } *              $             //The GetElement method creates a DOM element with the provided placeholder literal valuePanax NotoginsengTextfield.prototype.getelement=function(){ -                 varTextfield=document.createelement ("Input"); theTextfield.setattribute ("type", "text"); +Textfield.setattribute ("placeholder", This. DisplayText); A                 returnTextField; the             } +              -             //define the Emailfield class for creating <input type= "email" > Table cells $             functionEmailfield (displayText) { $                  This. displaytext=DisplayText; -             } -             //The GetElement method creates a DOM element with the provided placeholder literal value theEmailfield.prototype.getelement=function(){ -                 varEmailfield=document.createelement ("Input");WuyiEmailfield.setattribute ("type", "email"); theEmailfield.setattribute ("placeholder", This. DisplayText); -                 returnEmailfield; Wu             }; -              About             //define ButtonField "class" for creating <button> table cells $             functionButtonField (displayText) { -                  This. displaytext=DisplayText; -             } -             //The GetElement method creates a DOM element with the provided placeholder literal value AButtonfield.prototype.getelement=function(){ +                 varButton=document.createelement ("button"); theButton.setattribute ("type", "Submit"); -Button.innerhtml= This. DisplayText; $                 returnbutton; the};

Code Listing 5-2 demonstrates how to use the factory created in code listing 5-1 in your application.

Code listing 5-2 using Factory mode

1             //Use the factory to create a text entry Form field, an email form field, and a Submit button. Please note how we do not need to know2             //Create form fields in cases where the underlying "class" or their specific input is created. Formfieldfactory has abstracted this approach3             varTextfield=formfieldfactory.makefield ({type: "text", DisplayText: "Enter the first line of your address"}),4Emailfield=formfieldfactory.makefield ({type: "email", DisplayText: "Enter your email address"}),5Buttonfield=formfieldfactory.makefield ({type: "button", DisplayText: "Submit"});6             7             //when the Load event of the browser is triggered, the DOM element represented by the three newly created objects is added to the current page8Window.addeventlistener ("Load",function(){9                 varBodyelement=document.body;Ten                  One                 //Use the GetElement () method of each object to get a reference to its DOM element to add it to the page A Bodyelement.appendchild (Textfield.getelement ()); - Bodyelement.appendchild (Emailfield.getelement ()); - Bodyelement.appendchild (Buttonfield.getelement ()); the},false);

Using Factory mode is best when you need to simplify the creation of certain objects by masking more complex object creation methods in all the rest of the code.

5.2.2 Abstract Factory mode

Proficient in javascript--05 design mode: Create type

Related Article

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.