本质——唯一实例
一、what
一个类在整个系统中只有一个实例;
通过内部private构造方法创建;
多线程共享一个实例;
占用特定的内存区域;
常驻能内存;
二、why
在内存中只有一个对象,节省内存空间。避免频繁的创建销毁对象,可以提高性能。避免对共享资源的多重占用。可以全局访问。
三、how
内部类、饿汉、静态代码块都是利用了static的特性,还有利用Enum特性。
/**
* @Description: 饿汉模式,线程安全
* @date 2018-05-21 23:18
*/
public class HungerModel {
private static HungerModel hungerModel = new HungerModel();
private HungerModel(){}
public static HungerModel getInstance(){
return hungerModel;
}
}
/**
* @Description: 使用内部静态类实现单例
* @date 2018-05-21 23:25
*/
public class InnerClass {
private static class InnerClassCreater{
private static InnerClass innerClass = new InnerClass();
}
private InnerClass(){}
public static InnerClass getInstance(){
return InnerClassCreater.innerClass;
}
}
/**
* @Description: 懒汉模式单例的线程安全写法
* @date 2018-05-21 23:10
*/
public class LazyModel {
private static LazyModel lazyModel;
private LazyModel(){}
public static LazyModel getInstance(){
if(null != lazyModel){
}else{
// 模拟一些逻辑
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (LazyModel.class) {
if (null == lazyModel) {
lazyModel = new LazyModel();
}
}
}
return lazyModel;
}
}
/**
* @Description: 使用静态代码块实现单例
* @date 2018-05-21 23:33
*/
public class StaticModel {
private static StaticModel staticModel = null;
private StaticModel(){}
static{
staticModel = new StaticModel();
}
public static StaticModel getInstance(){
return staticModel;
}
}
/**
* @Description: 利用Enum特性,牛逼推荐的一种方式
* @date 2018-06-17 23:08
*/
public enum ResourceEnum {
INSTANCE;
private Resource instance;
ResourceEnum(){
instance = new Resource();
}
public Resource getResourceInstance(){
return instance;
}
}