Skip to content

Latest commit

 

History

History
50 lines (45 loc) · 1.21 KB

04.md

File metadata and controls

50 lines (45 loc) · 1.21 KB

js 面向对象初接触(4)

创建型 - 单例模式

单例模式定义

  1. 保证一个类仅有一个实例,并提供一个访问它的全局访问点。

单例模式何时使用

  1. 在JavaScript开发中,对于全局只需要实例出一个的对象,我们的实现往往使用单例。如:登录控制器,购物车,音乐播放器等一个工程需要使用多次的控制器或方法。

js 代码模拟

function Fn(name) {
    this.name = name;
}
Fn.prototype = {
    // constructor: "Fn",
    say() {
        console.log(this.name)
    }
}
// 判断系统是否已经有这个单例,如果有则返回,如果没有则创建。
let creator = function () {
    var obj;
    console.log(obj)
    return function (name) {
        if (!obj) {
            obj = new Fn(name);
        }
        return obj;
    }
}()

let tom = new creator('tom');
console.log(tom) // Fn {name: "tom"}
tom.say(); // tom
let jerry = new creator("jerry");
console.log(jerry) // Fn {name: "tom"}
console.log(tom === jerry) // true
jerry.say(); // tom

生成单例模式

let singleFn = function(fn) {
    let result;
    return function(...arg) {
        return result || (result = new fn(...arg));
    }
};