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

MySQL 5.7.31 64-bit free installation version tutorial diagram

1. Download Download address: https://dev.mysql.c...

Some experience sharing on enabling HTTPS

As the domestic network environment continues to ...

The role of MySQL 8's new feature window functions

New features in MySQL 8.0 include: Full out-of-th...

Summary of important mysql log files

Author: Ding Yi Source: https://chengxuzhixin.com...

Detailed tutorial of using stimulsoft.reports.js with vue-cli

vue-cli uses stimulsoft.reports.js (nanny-level t...

Docker image compression and optimization operations

The reason why Docker is so popular nowadays is m...

vue-cli configuration uses Vuex's full process record

Table of contents Preface Installation and Usage ...

How to hide and remove scroll bars in HTML

1. HTML tags with attributes XML/HTML CodeCopy co...

More Features of the JavaScript Console

Table of contents Overview console.log console.in...

How to deploy services in Windows Server 2016 (Graphic Tutorial)

introduction Sometimes, if there are a large numb...

How to let DOSBox automatically execute commands after startup

Using DOSBox, you can simulate DOS under Windows ...