单例模式:
保证对象在整个运行过程中仅存在一个实例。
1.构造方法私有化。2.提供对外部提供当前实例的public方法。
代码示例:单锁(不推荐使用),双检索(推荐),静态内部类(推荐)
/***
* @Author zzz_欢欢欢
*
* 单例模式
* 定义:保证一个类仅有一个实例,并提供一个访问它的全局访问点
*/
public class Sington_Main {
public static void main(String[] args) throws InterruptedException {
ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
for(int i=0;i<100;i++){
cachedThreadPool.execute(()->{
try {
System.out.println(Thread.currentThread().getName()+":"+Demo4.getInstance());
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
Thread.sleep(100);
}
}
}
//单例对象
class SingtonBean {}
//饿汉模式
class Demo1 {
private static SingtonBean singtonBean = new SingtonBean();
private Demo1() {
}
public static SingtonBean getInstance() {
return singtonBean;
}
}
//懒汉模式 --> 单锁
class Demo2 {
private static SingtonBean singtonBean;
private Demo2() {
}
public static SingtonBean getInstance(){
synchronized (Demo2.class){
if (singtonBean == null){
singtonBean = new SingtonBean();
}
return singtonBean;
}
}
}
//懒汉模式 --> 双检索
class Demo3 {
private volatile static SingtonBean singtonBean;
private Demo3(){}
public static SingtonBean getInstance(){
if (singtonBean == null){
synchronized (Demo3.class){
if (singtonBean == null){
singtonBean = new SingtonBean();
}
}
}
return singtonBean;
}
}
//静态内部类实现
class Demo4 {
private Demo4() {}
private static class SingtonInstance {
private static final SingtonBean SINGTON_BEAN = new SingtonBean();
}
public static SingtonBean getInstance(){
return SingtonInstance.SINGTON_BEAN;
}
}