定义
保证一个类仅有一个实例,并提供一个访问它的全局访问点。
使用方式
- 不允许其他程序用new 创建对象。
- 在类中创建一个本类实例。
- 对外提供一个方法让其他程序获取该对象
代码
- 懒汉式
调用方法时,才会建立对象,延迟加载,线程不安全。
public class Singleton {
private static Singleton s=null;
private Singleton(){
}
public static Singleton getInstance(){
if (s==null)
s=new Singleton();
return s;
}
}
线程安全的
public class Singleton {
private static Singleton s=null;
private Singleton(){
}
public static Singleton getInstance(){
if (s==null){//如果不为null,不用重复判断锁
synchronized (Singleton.class) {
if (s == null)
s = new Singleton();
}
}
return s;
}
}
2.饿汉式
类一加载,对象就建立了
public class Singleton {
private static Singleton s=new Singleton();
private Singleton(){
}
public static Singleton getInstance(){
return s;
}
}