This article has participated in the Denver Nuggets Creators Camp 3 “More Productive writing” track, see details: Digg project | creators Camp 3 ongoing, “write” personal impact

preface

To put it simply, when solving problems, predecessors encountered similar problems frequently and had to write the same code each time, which was annoying and repeated too much. So you start thinking about how you can organize this repetitive code, take something, automate it, don’t have to do so many things every time, and that’s a design pattern

Of course, this is only part of the problem of design patterns. Part of the problem is how to make code more maintainable, more reusable, more robust. But no one design pattern can solve all problems, so there are multiple design patterns with different priorities. The design patterns associated with creating a class are:

  1. Constructor pattern
  2. The prototype pattern
  3. Builder pattern
  4. The factory pattern
  5. Abstract Factory pattern
  6. The singleton pattern

Several design patterns

Constructor pattern

// Create a class to construct objects uniformly
function Student(name,gender,score){
    this.name=name;
    this.gender=gender;
    this.score=score;
    this.qulity=100;
    this.sumScore=function(){
            return this.score + this.qulity; }}var alice = new Student('alice'.'woman'.80);
var tom = new Student('tom'.'male'.88);
console.log(alice,tom);


//es6
class Student{
    constructor(name,gender,score){
        this.name=name;
        this.gender=gender;
        this.score=score;
        this.quality=100;
    }
    sumScore(){
        return this.score + this.qulity; }}let alice = new Student('alice'.'woman'.80);
let tom = new Student('tom'.'male'.88);
console.log(alice,tom);
Copy the code

The prototype pattern

function Student(name,gender,score){
	this.name = name;
	this.gender = gender;
	this.score = score;
}
// Use prototypes to extract common properties and methods without putting them in the constructor and executing the code every time
Student.prototype.quality = 100;
Student.prototype.sumScore = function (){
	return this.score + this.qulity;
}
var alice = new Student('alice'.'woman'.80);
var tom = new Student('tom'.'male'.88);
console.log(alice,tom);
Copy the code

Prototype pattern application

<script type="text/javascript">
    var rootElement = document.getElementById('table_roster');
/ / the constructor
    function Student(name,gender,score){
        this.name = name;
        this.gender = gender;
        this.score = score;
    this.mount();
    }
// Stereotypes have attributes and methods
    Student.prototype.qulity = 100;
    Student.prototype.sumScore = function (){
        return this.score + this.qulity;
    }
// Mount the data to the page
    Student.prototype.mount = function(){
        var tr = document.createElement('tr');
        tr.innerHTML='<td>'+this.name+'<td>' +
                                '<td>'+this.gender+'<td>' +
                                '<td>'+this.score+'<td>' +
                                '<td>'+this.qulity+'<td>' +
                                '<td>'+this.sumScore()+'<td>';
        rootElement.appendChild(tr);
    }
    var alice = new Student('alice'.'woman'.80);
    var tom = new Student('tom'.'male'.88);

------------------------------------------------------------------------------------------
/ / es6 writing
var rootElement = document.getElementById('table_roster');
    class Student{
        / / the constructor
        constructor(name,gender,score){
                this.name = name;
                this.gender = gender;
                this.score = score;
                this.quality=100;
                this.mount();// Perform the mount
        }
        // Calculate the total score
        sumScore(){
                return this.score + this.quality;
        }
        / / a mount
        mount(){
                var tr = document.createElement('tr');
                tr.innerHTML='<td>'+this.name+'<td>' +
                                        '<td>'+this.gender+'<td>' +
                                            '<td>'+this.score+'<td>' +
                                            '<td>'+this.quality+'<td>' +
                                            '<td>'+this.sumScore()+'<td>'; rootElement.appendChild(tr); }}var alice = new Student('alice'.'woman'.80);
    var tom = new Student('tom'.'male'.88);
</script>
Copy the code

Builder pattern (Creator pattern)

function Student(){}// Constructor class
function StudentBuilder(){
    this.student=new Student();
    this.setName=function(name){
            this.student.name = name;
    }
    this.setGender=function(gender){
            this.student.gender = gender;
    }
    this.setHairLength=function(hairlength){
            this.student.hairlength = hairlength;
    }
    this.build= function(){
            return this.student; }}// Create a builder object to operate on
var builder = new StudentBuilder();
builder.setName('alice');
builder.setGender('woman');
builder.setHairLength(2);
var alice = builder.build();
console.log(alice);

------------------------------------------------------------------------------------------
/ / es6 writing
class Student{}// Constructor class
class StudentBuilder{
    constructor(){
            this.student=new Student();
    }
    setName(name){
            this.student.name = name;
    }
    setGender(gender){
            this.student.gender = gender;
    }
    setHairLength(hairlength){
            this.student.hairlength = hairlength;
    }
    build(){
            return this.student; }}// Create a builder object to operate on
let builder = new StudentBuilder();
builder.setName('alice');
builder.setGender('woman');
builder.setHairLength(2);
let alice = builder.build();
console.log(alice);
Copy the code

Builder pattern application

<! DOCTYPEhtml>
<html>
<head>
    <title>demo</title>
</head>
<body>
    <form id="create">
            <div>Name:<input type="text" name="studentName" autofocus><br>
            </div>
            <div>Gender:<input type="radio" name="gender" value="Female" checked>female<input type="radio" name="gender" value="Male">male<br>
            </div>
            <div>Age:<input type="number" name="age">
            </div>
            <input type="submit" value="Submit">
    </form>

<script type="text/javascript">
    var createForm = document.getElementById('create');
    init();
    function init(){
            createForm.addEventListener('submit'.function(e){
                    e.preventDefault();
                    var name = document.querySelector('[name="studentName"]').value;
                    var gender = document.querySelector('[name="gender"]:checked').value;
                    var age = document.querySelector('[name="age"]').value;
                    var bulider = new StudentBuilder();
                    bulider.setName(name);
                    bulider.setGender(gender);
                    bulider.setAge(age);
                    var student = bulider.bulid();
                    console.log(student);
            });
    }
    function Student(){}// Constructor class
    function StudentBuilder(){
            this.student=new Student();
    }
    StudentBuilder.prototype.setName=function(name){
            this.student.name=name;
    }
    StudentBuilder.prototype.setGender=function(gender){
            this.student.gender=gender;
    }
    StudentBuilder.prototype.setAge=function(age){
            this.student.age=age;
    }
    StudentBuilder.prototype.bulid=function(){
            return this.student;
    }	
</script>
</body>
</html>
Copy the code

The factory pattern

<script type="text/javascript">
    function Student(name,subjects){
            this.name=name;
            this.subjects=subjects;
    }
    Var Alice = new Student(' Alice ',[' politics ',' history ',' geography ']);
    var alice = factory('alice'.'LIBERAL_ART');
    var tom= factory('tom'.'SCIENCE');
    console.log(alice,tom);
    // Create a factory
    function factory(name,type){
            if (type=='LIBERAL_ART') {
                    return new Student(name,['political'.'history'.'geographic']);
            }else{
                    return new Student(name,['mathematics'.'physical'.'chemistry']); }}</script>-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- / / the application of the factory pattern<! DOCTYPEhtml>
<html>
<head>
    <meta charset="utf-8">
    <title>demo</title>
</head>
<body>
    <form id="createStudent">
            <div>Name:<input type="text" name="name">
            </div>
            <div>
                    <select name="type">
                            <option value="Liberal arts">The liberal arts</option>
                            <option value="Science">science</option>
                            <option value="Sports">sports</option>
                    </select>
            </div>
            <button type="submit">submit</button>
    </form>


<script type="text/javascript">
    init();
    function init(){
            var form=document.getElementById('createStudent');		
            form.addEventListener('submit'.function(e){
                    e.preventDefault();
                    var name = document.querySelector('[name="name"]').value;
                    var type = document.querySelector('[name="type"]').value;
                    var student = studentFactory(name,type);
                    console.log(student);
            });
    }
    / / class
    function Student(name,subjects){
    this.name=name;
    this.subjects=subjects;
}
/ / factory
function studentFactory(name,type){
    if (type=='liberal arts') {
        return new Student(name,['political'.'history'.'geographic']);
    }else if(type=='science') {return new Student(name,['mathematics'.'physical'.'chemistry']);
    }else{
            return new Student(name,['run'.'rope'.'jump']); }}</script>

Copy the code

Abstract Factory pattern

<! DOCTYPE html><html>
<head>
    <meta charset="utf-8">
    <title>demo</title>
</head>
<body>
<script type="text/javascript">
    function Student(){
            this.intro = 'I'm a student';
    }
    function Teacher(){
            this.intro = 'I'm a teacher';
    }
    function studentFactory(){
            return new Student();
    }
    function teacherFactory(){
            return new Teacher();
    }
    // Abstract factory, this province does not produce things, but organizes factories.
    function userAbstractFactory(factory){// Or userProducer
            switch(factory){
                    case 'student':
                            return studentFactory;
                            break;
                    case 'teacher':
                            return teacherFactory;
                            break;
                    default:
                            throw 'There is no such factory';
                            break; }}var factory=userAbstractFactory('student');
    console.log(factory());
</script>
</body>
</html>
Copy the code

The singleton pattern

Anyway, new returns only one instance, and the second new returns the good object of the first new.

function Resource(){
    // If it is not the first time new (instance must exist)
    if (Resource.instance) {
            return Resource.instance;
    }else{// Otherwise instance does not exist
            // Assemble a new object
            this.balance=100;
            // Save it to the Resource machine
            Resource.instance=this; }}var r= new Resource();
console.log(r);
r.balance=50;
console.log(r);
//....
Copy the code