设计模式-建立型模式-单例模式es6
建立型模式隐藏类的实例和建立细节,经过隐藏对象如何建立组合在一块儿达到整个系统独立。web
确保同一时刻只有一个实例被访问。
Ensure a class has only one instance, and provide a global point of access to it. 确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例。数据库
在运行的时候直接加载实例化对象设计模式
package demo2; // 演示单例模式 public class Singleton { // 在一加载的时候直接加载 private final static Singleton singleton = new Singleton(); // 确保不会被实例化 private Singleton() { } // 其余方法,建议使用static public static Singleton getSingleton() { return singleton; } }
package demo2; public class Test { public static void main(String[] args) { Singleton.getSingleton(); } }
使用这个会形成在未使用的时候,出现大量的内存占用。多线程
即,在使用的时候实例化对象。ide
package demo2; // 演示单例模式 public class Singleton { // 在一加载的时候直接加载 private static Singleton singleton; // 确保不会被实例化 private Singleton() { if (Singleton.singleton == null) Singleton.singleton = new Singleton(); } // 其余方法,建议使用static public static Singleton getSingleton() { return singleton; } }
package demo2; public class Test { public static void main(String[] args) { Singleton.getSingleton(); } }
当在多线程的时候,因为不是final,会形成出现多个实例化对象。使用同步锁。工具
package demo2; // 演示单例模式 public class Singleton { // 在一加载的时候直接加载 private static Singleton singleton; // 确保不会被实例化 private Singleton() { if (Singleton.singleton == null) { synchronized(this) { // 同步 // 若是此时已经有实例化对象,则不须要再次生成实例化对象 if (Singleton.singleton == null) { Singleton.singleton = new Singleton(); } } } } // 其余方法,建议使用static public static Singleton getSingleton() { return singleton; } }
web页面计数器,此时使用单例模式
访问IO和数据库资源的时候,使用单例模式
工具类,使用单例模式
数据库的主键this
var Singleton = function(name){ this.name = name; } // 添加方法 Singleton.prototype.getName = function(){ return this.name; } // 构造 Singleton.getSingleton = function(name){ if (!Singleton.instace){ this.instace = new Singleton(); } return this.instace; }
class Singleton{ constructor(){ this.name = ""; } static getSingleton(){ if(!this.instance){ this.instance = new Singleton(); } return this.instance; } getName(){ return this.name; } } let a = Singleton.getSingleton(); let b = Singleton.getSingleton(); console.log(a === b);
制做一个登录弹窗的登陆界面
一个类,该类为登陆框,构造方法里,第一次点击,构造出登陆对象,第二次点击,不构造,使用的是单例模式,并设置几个方法,为显示方法,关闭方法。最后绑定事件。spa