let timeTool = { name:'处理时间工具库',getISODate:function() {},getUTCDate:function() {}}
惰性单例模式
只有在需要使用单例时候才实例化单例,称为惰性单例。这样声明单例时候可以占用比较小的内存。
var mySingleton = (function () {// Instance stores a reference to the Singletonvar instance;functioninit() {// Singleton// Private methods and variablesfunctionprivateMethod(){console.log( "I am private" ); }var privateVariable ="Im also private";var privateRandomNumber =Math.random();return {// Public methods and variablespublicMethod:function () {console.log( "The public can see me!" ); }, publicProperty:"I am also public",getRandomNumber:function() {return privateRandomNumber; } }; }returnfunction(){// Get the Singleton instance if one exists// or create one if it doesn'tif ( !instance ) { instance =init(); }return instance; };})();var myBadSingleton = (function () {// Instance stores a reference to the Singletonvar instance;functioninit() {// Singletonvar privateRandomNumber =Math.random();return {getRandomNumber:function() {return privateRandomNumber; } }; }return {// Always create a new Singleton instancegetInstance:function () { instance =newinit();return instance; } };})();// Usage:var singleA =mySingleton();var singleB =mySingleton();console.log( singleA.getRandomNumber() ===singleB.getRandomNumber() ); // truevar badSingleA =myBadSingleton.getInstance();var badSingleB =myBadSingleton.getInstance();console.log( badSingleA.getRandomNumber() !==badSingleB.getRandomNumber() ); // true// Note: as we are working with random numbers, there is a// mathematical possibility both numbers will be the same,// however unlikely. The above example should otherwise still// be valid.// 这里还有一个缺点:客户端使用时候需要特别注明(研究代码)才知道getInstance是唯一的访问入口,而MyBadSingleton只需要调用函数就可以获取单例}