JavaScript design mode-Factory mode

Source: Internet
Author: User

JavaScript design mode-Factory mode I understand the factory pattern, which is to provide a pattern of multiple classes related to a unified portal, so that you can get multiple classes from one portal and increase productivity.

However, there are three types of implementations for the factory model: Simple Factory mode, factory method mode and abstract Factory mode. They are based on a certain improvement on their own.

Simple Factory mode

It is also called the Static Factory mode (simple Factory Patter), which is used primarily for creating 同一类的对象 .

Application: If asked to write some ball games, then the general situation we will do this:

var Football = function(){    this.name = "football"; ....}var Basketball = function(){ this.name = "basketball"; ....}

There are some flaws in this notation: 返回了多个类,不便于他人使用. so we consider encapsulating these similar classes in a factory, with our simple factory model:

var ballfactory;! (function) {ballfactory =functionTYPE,CFG) {var Football =functionCFG) {THIS.name =' Football ';Console.log (THIS.name +"In the prototype"); }; Football.prototype = {Callfunction){Console.log (THIS.name)},Sellfunction){} };var Basketball =function (cfg) {this.name = " basketball "; console.log (this.name);}; var cfg = cfg | | {}; switch (type) {case  ' Football ': Span class= "Hljs-keyword" >return new Football (CFG); break; case  ' basketball ': return new Basketball (CFG); break;} };}) (); var Afootball = ballfactory ( ' football '); Afootball.call ();   

So using ballfactory to wrap this stuff up for other people would avoid returning multiple classes, so this is the problem that simple Factory mode wants to solve:
统一创建的入口.

Of course, in the actual use of the process, we will use some other techniques:

If there is a lot of repetition in the product of a factory, then we need to abstract the duplicated parts into a common part, and the different parts into the switch:

var GetChildren =functionCFG) {cfg = cfg| | {};this.name = cfg.name; this.height = cfg.height; This.speak = function () {}; //Pull out a different part of switch (cfg.gender) { case ' boy ': this.gender = Cfg.gender; This.moustouch = ...;; //Special part break ; case "Girl": this.gender = Cfg.gender, ... break; return this ;} var aboy = GetChildren ({...});              
Factory method Mode

On the basis of the simple factory model, we have solved the problem of non-unification of the entrance, but there is still one problem not solved:

Adding a new class requires modifying the multipart: first we need to add to the Ballfactory factory how to implement it, and then add it to the switch section; So this is a modification requirement and we need to modify multiple places.

So let's see if we can try to be more abstract and minimize the need for modification ;

var ballfactory =functionTYPE,CFG) {THIS.name = Cfg.name;The common part is here.Returnthis[type] (cfg);}; Ballfactory.prototype = {football: function (cfg) {console.log ( " Add the unique content associated with football "+this.name); }, basketball:function (cfg) {console.log ( " Add the unique content associated with basketball "+this.name); }}; var aball = new ballfactory ( " Football ", {name:" football "}); //football in the prototype          

So here's a return this[type](cfg) way to automatically replace the previous switch. You need to add content in the future only need to modify ballfactory prototype.

Of course, we can also add one 安全模式 to solve the problem if you do not precede the constructor with new. The solution is to encapsulate new in the constructor :

 var ballfactory = function (type,cfg) {if (! ( this instanceof ballfactory)) {return new ballfactory (TYPE,CFG); //more than one line to judge that: if you do not bring new, I will help you to return a new, good; this.name = Cfg.name; return this[type] (cfg);}; var Aball = ballfactory ( "football", { "football"}); //if you drop it, new will execute normally;           

So what we can see is that we use the simple factory model to solve the problem of non-uniformity of the portal , and then use the Factory mode to solve the problem of the change location is not uniform .

Abstract Factory mode

In general, abstract factories in large projects to use more, presumably the idea is to design the interface in the parent (no specific implementation), the implementation of the specific until the sub-class rewrite.

Here's an example of a Zhang Jongming <javascript design pattern >:

var Car =function){}; Car.prototype = {GetPrice:function){Thrownew error ( "abstract method cannot be called")}, getspeed:function ( throw new error ( "abstract method cannot be called")}}; //here with Object.create () inheritance, the subclass to the parent class will have one more intermediate transition function, temp () {}, to prevent the prototype of subclasses from overriding the parent class; ABMW = object.create (Car.prototype); Abmw.getprice (); //abstract method cannot call Abmw.getprice =  function (console.log ( "I am Getting price ");}; Abmw.getprice (); //i am getting price           

The parent class defines the interface, and the implementation is deferred until the child class is implemented.

So, in summary:

The simple factory model solves the problem of non-unification of the entrance ,

The factory model solves the problem of the change of location ,

The abstract factory pattern solves the problem of sub-class implementations that are not canonical.

At present, our new revision of the mobile side form block logic and rendering separation, also similar to a form page out into a factory, the factory has more than 20 different controls, each control to inherit the form of the class.

JavaScript design mode-Factory mode

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.