1、饿汉模式(静态变量)
package com.test.singletonMode.type01;
/**
* @author :Breeze
* @date :Created in 2020/11/15 20:11
* @description:
*/
public class SingletonTest01 {
public static void main(String[] args) {
Singleton instance = Singleton.getInstance();
}
}
/**
* 饿汉模式(静态变量)
*/
class Singleton {
//构造器私有化,在外不能使用new来创建对象
private Singleton() {
}
//本类内部创建对象,类加载时,创建
private static final Singleton INSTANCE = new Singleton();
//对外提供获取实例的方法
public static Singleton getInstance(){
return INSTANCE;
}
}
2、懒汉模式,使用才创建,但是有隐患,线程不安全
package com.test.singletonMode.type02;
/**
* @author :Breeze
* @date :Created in 2020/11/15 20:24
* @description:
*/
public class SingletonTest02 {
public static void main(String[] args) {
Singletion instance = Singletion.getInstance();
}
}
/**
* 懒汉模式,使用才创建,但是有隐患,线程不安全
*/
class Singletion {
private Singletion() {
}
private static Singletion INSTANCE;
public static Singletion getInstance() {
if (INSTANCE == null) {
INSTANCE = new Singletion();
}
return INSTANCE;
}
}
3、懒汉模式,使用才创建,线程安全,但是效率低
package com.test.singletonMode.type03;
/**
* @author :Breeze
* @date :Created in 2020/11/15 20:24
* @description:
*/
public class SingletonTest03 {
public static void main(String[] args) {
Singletion instance = Singletion.getInstance();
}
}
/**
* 懒汉模式,使用才创建,线程安全,但是效率低
*/
class Singletion {
private Singletion() {
}
private static Singletion INSTANCE;
public static synchronized Singletion getInstance() {
if (INSTANCE == null) {
INSTANCE = new Singletion();
}
return INSTANCE;
}
}
4、懒汉,双重检查
package com.test.singletonMode.type04;
/**
* @author :Breeze
* @date :Created in 2020/11/15 20:38
* @description:
*/
public class SingletonTest04 {
public static void main(String[] args) {
Singleton instance = Singleton.getInstance();
}
}
/**
* 懒汉,双重检查,既能解决性能问题,又能解决线程不安全的问题
*/
class Singleton {
private Singleton() {
}
private static volatile Singleton INSTANCE;
public static Singleton getInstance() {
if (INSTANCE == null) {
synchronized (Singleton.class) {
if (INSTANCE == null) {
INSTANCE = new Singleton();
}
}
}
return INSTANCE;
}
}
5、使用静态内部类
package com.test.singletonMode.type05;
/**
* @author :Breeze
* @date :Created in 2020/11/15 20:47
* @description:
*/
public class SingletonTest05 {
public static void main(String[] args) {
Singleton instance = Singleton.getInstance();
}
}
/**
* 使用静态内部类
* 静态内部类好处: 1、外部Singleton加载时,静态内部类并不会加载,只有在用到静态内部类时,才回家再
* 2、类加载时,是线程安全的
*/
class Singleton{
private Singleton(){
}
public static class SingletionInstance{
public static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance(){
return SingletionInstance.INSTANCE;
}
}