Facotry A pattern is a creative pattern , He's different from normal coding habits , Call each constructor as shown .Factory Patterns provide a common interface to create objects .

One Factory Schema compresses the way all objects are created , Reduce the coupling of this factory to other objects .

Use a piece of code to demonstrate , We use it Factory Model to do a car factory program .

// Factory 
var Factory = {
var carFactory;
case 'car':
carFactory = Object.create(this.Car);
case 'car':
carFactory = Object.create(this.Truck);
return carFactory;
}, // Automobile
Car: {
doors: 4,
}, // Trucks
Truck: {
doors: 6,
color: 'blue',
} // Other factory class codes
} // Instantiate a factory
var factory = Object.create(Factory); // Instantiate the car through the entrance to the factory
var car = factory.createVehicle('car');

As can be seen from the code , We don't use Object.create(Factory.Car) or Object.create(Factory.Truck) Show create corresponding instance , But with a createVehicle Function to manage , Call different car classes according to different parameters to create different instances . In this way , The following program will only rely on factory.createVehicle This entry function , Greatly reduced the coupling .

because IE8 Does not support Object.create, We can use MDN Provided polyfill Compatible processing .

// Polyfill
if (!Object.create) {
Object.create = function (o) {
if (arguments.length > 1) {
throw new Error('Object.create implementation only accepts the first parameter.');
function F() {}
F.prototype = o;
return new F();

Factory methods generally use an entry function , Application switch Statement to create different product instances , therefore , We don't have to think about how the factory implements it when we create instances .

The abstract factory is based on the premise that there are already several factories , Abstract a unified interface , It takes what these factories produce as the same kind . Abstract factory is more like a strategy .


javascript Pattern ——Factory More articles about

  1. 《JavaScript Pattern 》 Little copy of knowledge points ( On )

    Introduce Recently, I began to set a learning task for myself every week , The feedback of learning results is the output of an article , Keep a good record of your study . This week (02.25-03.03) My goal is <JavaScript Pattern > Learn chapter seven of , The opposite of learning results ...

  2. javascript Pattern (1)—— Code reuse

    The development of program cannot do without the reuse of code , Code reuse can reduce development and maintenance costs , When it comes to code reuse , I think about inheritance first , But inheritance is not the only way to solve code reuse , There are other reuse patterns, such as object composition . In this section, we'll talk about a variety of inheritance patterns to implement ...

  3. The factory method mode of six creation modes (Factory Method Pattern)

    problem : When using simple factory mode , If you add a new product class , You must modify the factory class , It violates the open close principle . Definition : Defines an interface for creating objects , Let subclasses decide which product class to instantiate . At this point, both the factory and the product have the same inheritance structure , Abstract property ...

  4. 【 Reading notes 】 read 《JavaScript Pattern 》 - Modern inheritance pattern of function reuse pattern

    The modern inheritance model can be expressed as : Any other pattern that doesn't need to be considered as a class . The modern way of inheritance #1 —— Classless inheritance mode of archetypal inheritance function object(o) { function F() {}; F.protot ...

  5. 【 Reading notes 】 read 《JavaScript Pattern 》 - Inheritance patterns like function reuse patterns

    The goal of class inheritance is through constructors Child() Get from another constructor Parent() Properties of , To create objects . 1. Class inheritance pattern #1 —— Default mode ( The prototype points to the parent function instance ) function Paren ...

  6. Preliminary discussion JavaScript Pattern series Stage summary and planning

    summary Unknowingly, I began to write JavaScript It's been half a month since the model series , I didn't expect to enlarge the dots one by one , So many things can be found . In the meantime, I'm afraid of JS I don't understand you very well and mislead you , Read a lot of books ( Personal feeling JS It's the hardest oo Language ), also ...

  7. Design patterns ( Two ) Factory mode Factory ( Creation type )

    There are three factory models : Simple factory model (Simple Factory) . Factory method model (Factory Method). Abstract factory pattern (Abstract Factory) // give an example : Examples of sending emails and text messages /* ...

  8. Design patterns ( One ) Factory mode Factory( Creation type )

    Design mode 1 Factory mode Factory In object oriented programming , The most common method is a new Operator produces an object instance ,new Operators are used to construct object instances . But in some cases , new There are some problems with operators generating objects directly . ...

  9. Design patterns ( One ) Factory mode Factory( Create type )

    Design mode 1 Factory mode Factory In object oriented programming , The most common method is a new Operator produces an object instance ,new Operators are used to construct object instances . But in some cases , new There are some problems with operators generating objects directly . ...

Random recommendation

  1. MySQL defect mysql_config file

    I'm going to crawl , install mysqldb Use of results pip Installation error stay centos-6.4 On pip install mysql-python, An error is as follows [sentry@kjtest111 mysql-python]$ ...

  2. Linux Learning notes (4)Linux Common command of authority management command

    (1)chmod chmod Commands are used to change file or directory permissions , The original meaning of English is change the permissions mode of a file, The path is /bin/chmod, Its grammatical form is : chmod ...

  3. POJ 3624 Charm Bracelet

    DP It's always been a pain in the heart , Not much said , This summer vacation is here . This summer vacation first DP topic ,01 knapsack problem . It means that there are Weight and value , But the weight you can bear is limited , Ask the greatest value you can bring . Let's make this question bigger , Even though I don't know what's wrong , ...

  4. About Eigen Library in Visual Studio2013 Error report in parameter alignment

    Error as follow: The specific problems and solutions are described as follows : ( To quote http://www.fx114.net/qa-278-97757.aspx) /************************ ...

  5. c# equals And == The difference between

    For value types , If the values of the objects are equal , Then the equality operator (==) return true, Otherwise return to false. about string Other reference types , If two objects refer to the same object , be == return true. about string ...

  6. 【 Maximum flow 】BAPC2014 A Avoiding the Apocalypse (Codeforces GYM 100526)

    Topic link : http://codeforces.com/gym/100526 http://acm.hunnu.edu.cn/online/?action=problem&type=show& ...

  7. [ACM] Nine degrees OJ 1553 The clock

    The time limit :1 second Memory limit :128 mega Special questions : no Submit :1733 solve :656 Title Description narration : Pictured , Given random moments , Find the angle between the hour hand and the minute hand ( The angle corresponding to the inferior arc ). Input : The input includes multiple sets of test data . Number of tests per group ...

  8. html5 Store data locally , Achieve automatic login function

    background : Meet a requirement in the project : After the user logs in , The website automatically saves users id Store locally , The next time you open a web page , adopt id Determine whether to log in . Technical solution : stay HTML5 in , Local storage is a window Properties of , Include lo ...

  9. POJ1222 The problem of lights out

    A thousand years old problem , I used to do it with enumeration , Now let's do it with Gaussian elimination The free element is directly made into 0 that will do #include<cstdio> #include<cstdlib> #include<algorithm ...

  10. H5 Poster making practice

    introduction Has been in a state of rapid development since , There was an urgent need last week , by 38 Make an activity page on women's Day , The main function is to generate posters , For the first time , I'm also a half bucket front end , What will happen here . Trampled pit , How to share , It's not in place ...