单例模式(creational 3)

210 阅读1分钟

1.3 单例模式(singleton)

  • 确保一个类最多只有一个实例,并提供一个全局访问点 (预加载 懒加载?)
function Person() {

  if (typeof Person.instance === 'object')
    return Person.instance;

  Person.instance = this;

  return this;
}

module.exports = Person;

测试用例

const expect = require('chai').expect
const Person = require('../src/creational/singleton/singleton');

describe('单例模式测试', () => {
	it('单个实例', () => {
		var john = new Person()
		var john2 = new Person()

		expect(john).to.equal(john2)
	})
})

es6 实现

class Person {
  constructor() {
    if (typeof Person.instance === 'object') {
      return Person.instance;
    }
    Person.instance = this;
    return this;
  }
}

export default Person;

const expect = require('chai').expect
import Person from '../src/creational/singleton/singleton_es6';

describe('单例模式测试 es6', () => {
	it('单个实例 es6', () => {
		var john = new Person()
		var john2 = new Person()

		expect(john).to.equal(john2)
		expect(john === john2).to.be.true
	})
})