享元模式(Flyweight Pattern)

享元模式以共享的形式高效地支持大量细粒度对象的重用。
享元模式主要用于减少创建对象的数量,以减少内存占用和提高性能。
一般将享元类中的内部状态进行处理变成享元类的成员变量,而外部状态通过注入的方式进行处理。
它和单例模式的区别是单例模式只有一个对象一个实例,而享元模式有n个实例。享元模式主要是为了节约内存空间提升性能,而单例模式主要是为了共享状态。

const student = function(id, name, age, grade, phone) {
  this.id = id;
  this.name = name;
  this.age = age;
  this.grade = grade;
  this.phone = phone;
  this.getInfo = function() {
    return `${this.id}${this.name}${this.age}${this.phone}`
  }
};

const studentInfo = function() {
  this.create = function(id, name, age, grade, phone) {
    let s = studentFactory(id, name);
    s.age = age;
    s.grade = grade;
    s.phone = phone;
    return s;
  }
};

const studentFactory = (function() {
  let s = {};
  return function(id, name) {
    if (s[id + name]) {
      console.log("调用已有对象");
      return s[id + name];
    } else {
      const newStudent = new student(id, name)
      s[id + name] = newStudent;
      console.log("新建对象");
      return newStudent;
    }
  }
})();

let s = new studentInfo();
let list = [];

for (let i = 0; i < 100; i++) {
  list.push(s.create("1", "shada", "18", "1", "123"));
}

console.log(list[0]);
console.log(list[0].getInfo());

你可能感兴趣的:(享元模式(Flyweight Pattern))