一、饿汉式
package com.lh.study.single;
/**
* @ClassName HungryOne
* @Description
* @Date 2018/12/8 11:49
* @Aurhor liang.hao
*/
public class HungryOne {
private HungryOne(){
}
private static HungryOne hungryOne = new HungryOne();
/*
* @Author liang.hao
* @Description 单例模式,饿汉式,容易照成内存浪费
* @Date 11:50 2018/12/8
* @Param []
* @return com.lh.study.single.HungryOne
**/
public static HungryOne getInstance(){
return hungryOne;
}
}
二、懒汉式(非线程安全)
package com.lh.study.single;
/**
* @ClassName LazyOne
* @Description
* @Date 2018/12/8 11:47
* @Aurhor liang.hao
*/
public class LazyOne {
private LazyOne(){
}
private static LazyOne lazyOne = null;
/*
* @Author liang.hao
* @Description 单例模式,线程不安全
* @Date 11:50 2018/12/8
* @Param
* @return
**/
public static LazyOne getInstance(){
if(lazyOne == null){
lazyOne = new LazyOne();
return lazyOne;
}
return lazyOne;
}
}
三、懒汉式(线程安全)
package com.lh.study.single;
/**
* @ClassName LazyTwo
* @Description
* @Date 2018/12/8 12:18
* @Aurhor liang.hao
*/
public class LazyTwo {
private LazyTwo() {
}
private static LazyTwo lazyTwo = null;
/*
* @Author liang.hao
* @Description 单例模式,同步锁,线程安全,但是性能差
* @Date 12:16 2018/12/8
* @Param []
* @return com.lh.study.single.LazyOne
**/
public synchronized static LazyTwo getInstance() {
if (lazyTwo == null) {
lazyTwo = new LazyTwo();
return lazyTwo;
}
return lazyTwo;
}
}
四、懒汉式(匿名内部类,最优推荐)
package com.lh.study.single;
/**
* @ClassName LazyThree
* @Description
* @Date 2018/12/8 12:20
* @Aurhor liang.hao
*/
public class LazyThree {
private boolean flag = false;
private LazyThree() {
synchronized (LazyThree.class) {
if (!flag) {
flag = true;
} else {
throw new RuntimeException("单例被入侵");
}
}
}
/*
* @Author liang.hao
* @Description
* @Date 12:29 2018/12/8
* @Param []
* @return com.lh.study.single.LazyThree
**/
public static final LazyThree getInstance() {
/**内部类默认不加载,当使用的时候才会加载,这样既避免了内存浪费,也避免了线程不安全*/
return LazyHolder.LAZY;
}
private static class LazyHolder {
private static final LazyThree LAZY = new LazyThree();
}
}
五、注册式(spring 中使用的单例模式)
package com.lh.study.single;
import java.io.Serializable;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* @ClassName RegisterOne
* @Description
* @Date 2018/12/8 12:35
* @Aurhor liang.hao
*/
public class RegisterOne {
private static Map<String , Object> beanMap = new ConcurrentHashMap<String , Object>();
public static Object getBean(String name){
if(beanMap.containsKey(name)){
return beanMap.get(name);
}else{
Object obj = null;
try {
obj = Class.forName(name).newInstance();
beanMap.put(name , obj);
return obj;
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return obj;
}
}
}