Common JavaScript Design Patterns (ii) Factory (factory) mode

Source: Internet
Author: User

Factory creates objects by providing a common interface, and we can also specify the type of object instances we want to create.

Suppose you now have a car factory vehiclefactory, which supports the creation of object instances of car and truck types and now requires the creation of objects of the specified type through this factory, then we do not need to create this specified object by directly using the new operator or through other creative constructors. , we just need to inform vehiclefactory what type of object instance we need, and then Vehiclefactory will return the object instance of the type we need.

Code implementation:

//constructors for car and trunkfunctionCar (options) { This. doors=options.doors| | 4;  This. state=options.state| | " Brand new ";  This. color=options.color| | " Black;}functionTrunk (options) { This. wheelsize=options.wheelsize| | ' Large;  This. color=options.color| | " Yellow;  This. state=options.state| | " Brand new ";}//Define Vehiclefactory Factoryfunctionvehiclefactory () {}//define how the factory creates instancesvehiclefactory.prototype.createvehicle=function(options) {Switch(options.vehicletype) { Case"Car": This. Vehicleclass=car; Break;  Case"Trunk": This. Vehicleclass=trunk; Break; }    return New  This. Vehicleclass (options);};//Create a factory instance that generates a carLet carfactory=Newvehiclefactory (); let Car1=carfactory.createvehicle ({vehicletype:"Car", Color:"White", Doors:6}); Console.log (CAR1);//{doors:6,state: "Brand new", Color: "White"}

Common JavaScript Design Patterns (ii) Factory (factory) mode

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.