javascript 享元模式

171 阅读1分钟

享元模式(Flyweight Pattern)主要用于减少创建对象的数量,以减少内存占用和提高性能。这种类型的设计模式属于结构型模式,它提供了减少对象数量从而改善应用所需的对象结构的方式。

例如:
需求 : 在开学季,家里蹲大学,有大量的同学需要入学登记

方式1: 不使用享元模式

 var student = function (school,profession,address,userName,phone,id,enterDate) {
        this.school = school;
        this.profession = profession;
        this.address = address;
        this.userName = userName;
        this.phone = phone;
        this.id = id;
        this.enterDate = enterDate;
        this.getInfo = function () {
            return "学校:"+this.school+"专业:"+this.profession+"地址:"+this.address+"学生名:"+this.userName+"电话:"+this.phone+"学号:"+this.id+"入学时间:"+this.enterDate;
        }
    };


    /*
    * 家里蹲大学有500000个学生
    *
    * */

    var studentList = [];
   for(var i=0;i<5000000;i++){
         studentList.push(new student("家里蹲","计算机","成都","zs","13132167257","1809131","2018-09-01"));
    }
12345678910111213141516171819202122231234567891011121314151617181920212223

方式2 享元模式方式:

  var student = function (school,address,profession,userName,phone,id,enterDate) {
        this.school = school;
        this.profession = profession;
        this.address = address;
        this.userName = userName;
        this.phone = phone;
        this.id = id;
        this.enterDate = enterDate;
        this.getInfo = function () {
            return "学校:"+this.school+"专业:"+this.profession+"地址:"+this.address+"学生名:"+this.userName+"电话:"+this.phone+"学号:"+this.id+"入学时间:"+this.enterDate;
        }
    };
    var studentInfo = function () {
        this.createSudent=function (school,address,profession,userName,phone,id,enterDate) {
            var s = studentFactory(school,address);
            s["profession"] = profession;
            s["userName"] = userName;
            s["phone"] = phone;
            s["id"] = id;
            s["enterDate"] = enterDate;
        }
    }

    var studentFactory=function () {
        var s= {};
        return function (school,address) {
            if(s[school+address]){
                return s[school+address]
            }else{
                var newStudent =new student(school,address);
                s[school+address]=newStudent;
                return newStudent;
            }
        }
    };
    var si = new studentInfo();
    var list = [];

    for(var i=0;i<5000000;i++){
        list.push(si.createSudent("家里蹲","计算机","成都","zs","13132167257","1809131","2018-09-01"));
    }