JavaScript Factory Pattern Explained

JavaScript Factory Pattern Explained

Simple Factory

insert image description here

//Basketball base class var Basketball = function() {
    this.intro = 'Basketball is popular in the United States';
}
Basketball.prototype = {
    getMember: function() {
        console.log('Each team needs five players');
    },
    getBallSize: function() {
        console.log('Basketball is very big');
    }
}
//Football base class var Football = function() {
    this.intro = 'Football is popular all over the world';
}
Football.prototype = {
    getMember: function() {
        console.log('Each team needs 11 players');
    },
    getBallSize: function() {
        console.log('The football is very big');
    }
}
//Sports factory var SportsFactory = function(name) {
    switch (name) {
        case 'NBA':
            return new Basketball();
        case 'worldCup':
            return new Football();
    }
}
//When you need to create a football for the World Cup, just remember the sports factory sportsFactory, call and create var Footnall = SportsFactory('worldCup');
console.log(Footnall);
console.log(Footnall.intro);
Footnall.getMember();

insert image description here

insert image description here

//Factory mode function createBook(name, time, type) {
    var o = new Object(); //Create an object and expand the properties and methods of the object //This is the different part o.name = name; //Book name o.time = time; //Book publishing time o.type = type; //Book type //The following is the similar part o.getName = function() {
        console.log(this.name);
    };
    //Return the object return o;
}
//Create two books var book1 = new createBook('JS book', 2021, 'js');
var book2 = new createBook('CSS book', 2019, 'css');
book1.getName();
book2.getName();

insert image description here

insert image description here

Factory Method

insert image description here

var Demo = function() {}
Demo.prototype = {
    show: function() {
        console.log('successfully acquired');
    }
}
var d = new Demo();//Correctly create instance d.show(); //Successfully obtain var d = Demo();//Error creating instance d.show(); //Explosion 

insert image description here

insert image description here

var Demo = function() {
    if (!this instanceof Demo) {//Judge what this points to return new Demo();
    }
}
Demo.prototype = {
    show: function() {
        console.log('Safe mode class is really useful');
    }
}
var d = Demo();
d.show();

insert image description here

Safe Factory Methods

//Create factory class in safe mode var Factory = function(type, content) {
    if (this instanceof Factory) {
        var s = new this[type](content);
        return s;
    } else {
        return new Factory(type, content);
    }
}
//Set the base class for creating all types of data objects in the factory prototype Factory.prototype = {
    java: function(content) {
        //...
    },
    UI: function(content) {
        this.content = content;
        (function() {
            var div = document.createElement('div');
            div.innerHTML = content;
            div.style.border = '1px soild red';
            document.getElementById('container').appendChild(div);
        })(content);
    },
    php: function(content) {
        //...
    },
    javascript: function(content) {
        //..
    }
};
//Create object var data = [
    { type: 'javascript', content: 'Which js is the best' },
    { type: 'java', content: 'Which java is the best' },
    { type: 'UI', content: 'Which UI is the best' }
];
for (let index = 0; index < data.length; index++) {
    console.log(data[index].type);
    Factory(data[index].type, data[index].content);
}

insert image description here

Abstract Factory

insert image description here

var Car = function() {}
Car.prototype = {
    getPrice: function() {
        return new Error('Abstract method cannot be called');
    },
    getSpeed: function() {
        return new Error('Abstract method cannot be called');
    }
};

insert image description here

//Abstract factory method var VehicleFactory = function(subType, superType) {
    //Judge whether the abstract class exists in the abstract factory if (typeof VehicleFactory[superType] === 'function') {
        //Cache class function F() {};
        //Inherit parent class properties and methods F.prototype = new VehicleFactory[superType]();
        //Point the subclass constructor to the subclass subType.constructor = subType;
        //Subclass prototype inherits parent class subType.prototype = new F();
    } else {
        //If the abstract class does not exist, throw new Error('The abstract class was not created');
    }
};
//Car abstract class VehicleFactory.Car = function() {
    this.type = 'car';
}
VehicleFactory.Car.prototype = {
    getPrice: function() {
        return new Error('Abstract method cannot be called');
    },
    getSpeed: function() {
        return new Error('Abstract method cannot be called');
    }
};
//Bus abstract class VehicleFactory.Bus = function() {
    this.type = 'bus';
}
VehicleFactory.Bus.prototype = {
    getPrice: function() {
        return new Error('Abstract method cannot be called');
    },
    getPassengerNum: function() {
        return new Error('Abstract method cannot be called');
    }
}

insert image description here

//Abstract and Implementation//BMW car subclass var BMW = function(price, speed) {
    this.price = price;
    this.speed = speed;
};
//The abstract factory implements the inheritance of the Car abstract class VehicleFactory(BMW, 'Car');
BMW.prototype.getPrice = function() { //Rewrite method return this.price;
}
BMW.prototype.getSpeed ​​= function() {
    return this.speed;
};
//Yutong bus subclass var YUTONG = function(price, passenger) {
    this.price = price;
    this.passenger = passenger;
};
//The abstract factory implements the inheritance of the BUS abstract class VehicleFactory(YUTONG, 'Bus');
YUTONG.prototype.getPrice = function() {
    return this.price;
}
YUTONG.prototype.getPassengerNum = function() {
    return this.passenger;
};
//Instantiate the class var myBMW = new BMW('100w', '1000km/h');
console.log(myBMW.getPrice(), myBMW.getSpeed(), myBMW.type);

insert image description here

insert image description here

Summarize

This article ends here. I hope it can be helpful to you. I also hope that you can pay more attention to more content on 123WORDPRESS.COM!

You may also be interested in:
  • js simple factory mode usage example
  • Definition and usage analysis of factory pattern and abstract factory pattern in JavaScript design pattern
  • JavaScript Design Patterns – Principles and Application Examples of Simple Factory Patterns
  • JavaScript Design Patterns – Factory Pattern Principles and Application Examples
  • JS Design Pattern: A Brief Analysis of the Definition and Implementation of the Factory Pattern
  • Share the usage of 3 factory patterns in JavaScript

<<:  XHTML: Frame structure tag

>>:  Summary of Mysql exists usage

Recommend

JSONP cross-domain simulation Baidu search

Table of contents 1. What is JSONP 2. JSONP cross...

Detailed explanation of the life cycle of Angular components (Part 2)

Table of contents 1. View hook 1. Things to note ...

How to find and delete duplicate records in MySQL

Hello everyone, I am Tony, a teacher who only tal...

A small question about the execution order of SQL in MySQL

I encountered a sql problem at work today, about ...

How to detect Ubuntu version using command line

Method 1: Use the lsb_release utility The lsb_rel...

How to configure VMware virtual machine NAT mode

This article describes the VMware virtual machine...

Summary of Problems in Installation and Usage of MySQL 5.7.19 Winx64 ZIP Archive

Today I learned to install MySQL, and some proble...

MySQL 8.0 New Features - Introduction to the Use of Management Port

Table of contents Preface Connection Management A...

JavaScript canvas text clock

This article example shares the specific code of ...

How to modify the root password of mysql under Linux

Preface The service has been deployed on MySQL fo...

How to view the network routing table in Ubuntu

What are Routing and Routing Table in Linux? The ...

Thoroughly understand JavaScript prototype and prototype chain

Table of contents Preface Laying the foundation p...