1、单例模式:
一、懒汉式:
//懒汉式单例类.延迟加载,在第一次调用的时候实例化自己
public class SingleTon{
private static SingleTon instance;
private SingleTon(){}
public static synchronized SingleTon getInstance(){//这种方式在方法上加同步,每次调用该方法都要同步
if(instance==null){
instance = new SingleTon();
}
return instance;
}
}
public static SingleTon getInstance(){//双重检查锁定,只有第一次调用单例的时候才会做同步
if(instance==null){
synshronized(SingleTon.class){
if(instance==null){
instance = new SingleTon();
}
}
}
return instance;
}
public class SingleTon{//利用了classloader的机制来保证初始化instance时只有一个线程,所以也是线程安全的,同时没有同步的性能损耗
private static class LazyHolder{
private static SingleTon instane = new SingleTon();
}
private SingleTon(){}
public static SingleTon getInstance(){
return LazyHolder.instance;
}
}
二、恶汉式:
//饿汉式单例类.在类初始化时,已经自行实例化,天生线程安全
public class SingleTon{
private static SingleTon instance = new SingleTon();
private SingleTon(){}
public static SingleTon getInstance(){
return instance;
}
}