JS Factory Model Brief Introduction

Source: Internet
Author: User

What is a factory model? It's like a factory that can build cars, airplanes ..., by the external interface, by the customer to decide, to customize which product.

In JS, as a factory function/object, including cars, airplanes and other sub-classes, provide external interface, according to the parameters to return the instances of different subclasses

A simple example is as follows:

varfactory={car:function(name, size) { This. name=name;  This. size=size;  This. getname=function(){            return  This. Name}}, plane:function(name, size) { This. name=name;  This. size=size;  This. getname=function(){            return  This. Name}}, Makecar:function(name, size) {return New  This. Car (name, size)}, Makeplane:function(name, size) {return New  This. Plane (name, size)}, make:function(type, name, size) {return New  This[Type] (name, size)}}varo= factory.make (' Plane ', ' Boeing ', 1000) Console.log (O.getname ())

When to use:

1. Object building is complex

2. Need to rely on a specific environment to create different instances

3. Handling large numbers of small objects with the same attributes

Advantages:

Eliminate coupling between objects, place all instantiated code in one place to avoid code duplication

Disadvantages:

Most classes are best used with the new keyword and constructor to make the code easier and easier to read. Without having to look at the factory method to know

JS Factory Model Brief Introduction

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.