js實現單例模式
阿新 • • 發佈:2019-01-04
//singletone.js
class Singleton {
static GetSingleton( fn ) {
var instance;
return function () {
if ( !instance ) {
instance = new fn( ...arguments );
}
return instance;
};
}
}
module.exports = Singleton.GetSingleton;
//animal.js class Animal { constructor( name ) { this._name = name; } } module.exports = Animal;
//test.js const assert = require( 'assert' ); const singletone = require( '../src/singletone' ); const animal = require( '../src/animal' ); describe( 'Singletone', () => { describe( '#animal', () => { it( 'should be same.', () => { const singleAnimal = singletone( animal ); assert.equal( singleAnimal( 'dog' ), singleAnimal( 'cat' ) ); assert.equal( singleAnimal( 'dog' ), singleAnimal() ); const singleAnimal1 = singletone( animal ); assert.notEqual( singleAnimal( 'dog' ), singleAnimal1( 'dog' ) ); } ) } ) } )