1. 单例模式
也就是整个项目中,就只有这一个实例,但是这个单例模式不透明,我们不知道
该调用getInstance的方法
class Animal {
static instance;
static getInstance() {
// 如果不存在就创建一个 实例对象
if(!Animal.instance) {
Animal.instance = new Animal();
}
// 如果 存在就把这个实例 返回出去
return Animal.instance;
}
}
const a1 = Animal.getInstance();
const a2 = Animal.getInstance();
console.log(a1 === a2); // true
2.封装单例模式
这个样子 我们就可以创建不同的种类了,但是每个的实例都是指向自己的,从而得到了扩展
function Animal () {
}
function Coffee () {
}
Animal.prototype.hello = function () {
console.log("hello");
}
Coffee.prototype.hello = function () {
console.log("hello");
}
let createInstance = function (Constructor) {
let instance;
return function() {
if(!instance) {
Constructor.apply(this, arguments);
// 这个是把 this.__proto__ = Constructor.prototype,这个样子 就不会导致指向错误了
Object.setPrototypeOf(this, Constructor.prototype);
// 这个是把当前的 this原型赋值给他, 这个样子就可以判断,
// 虽然是不同的种类 但是种类的实例都是指向自己的
instance = this;
}
return instance;
}
}
let createAnimal = createInstance(Animal);
let a1 = new createAnimal();
let a2 = new createAnimal();
console.log(a1 === a2, "a"); // true a
let createCoffee = createInstance(Coffee);
let c1 = new createCoffee();
let c2 = new createCoffee();
console.log(c1 == c2, "c"); // true c
使用场景:
redux中的createStore 就是一个单例模式,在整个项目中,store实例都是只有一个实例
import createStore from "redux";
function reducer() {
}
let initState = {};
// 这个createStore 就是一个单例模式, 全局的store都是共享的
let store = createStore(reducer, initState);