JavaScript Factory mode

Source: Internet
Author: User
Tags compact

Factory mode

The purpose of the factory schema design is to create objects. It is usually implemented in a static method of a class or class, with the following objectives:
1. Perform a repeat operation when creating a similar object
2. Provide the factory customer with an interface to create objects at compile time without knowing the specific type (class).
Objects created through factory methods (or classes) are designed to inherit the same idea of the same parent object, which are specific subclasses that implement specialized functionality. Sometimes the public parent class is the same class that contains the factory method,

Code:

//Parent Constructorfunctioncarmaker () {}; CarMaker.prototype.drive=function(){    return' Vroom, I have ' + This. Doors + ' doors ';};//Static Factory MethodCarmaker.factory =function(type) {varConstr =type, Newcar; //if the constructor does not exist, an error occurs    if(typeofCARMAKER[CONSTR]!== ' function '){        Throw{name:' Error ', Message:constr+ "doesn ' t exist"        }    }    //causes the prototype to inherit from the parent class, but inherits only once    if(typeofCarmaker[constr].prototype.drive!== ' function ') {Carmaker[constr].prototype=Newcarmaker (); }    //to create a new instanceNewcar =NewCarmaker[constr] (); //Optionally call some methods and return ....    returnNewcar;};//define a specific car makerCarmaker.compact =function(){     This. Doors = 4;} Carmaker.convertible=function(){     This. Doors = 2;}; CARMAKER.SUV=function(){     This. Doors = 24;};varCorolla = Carmaker.factory (' Compact ');varSolstice = carmaker.factory (' convertible '));varCherokee = carmaker.factory (' SUV ')); Console.log (Corolla.drive ()); //The result is ' Vroom, I have 4 Doors 'Console.log (Solstice.drive ());//The result is ' Vroom, I have 2 Doors 'Console.log (Cherokee.drive ());//results for ' Vroom, I have doors '

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.