设计模式之一 单例设计模式demo
第一种:普通方式
单例设计模式代码:
package com.hn.singleton;
/***
* 单例设计模式
*/
public class Singleton {
//创建一个全局静态变量用来存放实例对象
private static Singleton instance;
//私有化构造方法,防止外界创建对象
private Singleton(){}
//对外界暴露获得实例对象的方法
public static Singleton getInstance(){
//判断是对象是否为空,
if (instance == null){
//为空则创建
return instance = new Singleton();
}
//不为空则直接返回
return instance;
}
}
测试代码如下:
@Test
public void testDemo(){
/*测试单例模式*/
Singleton singleton1 = Singleton.getInstance();
Singleton singleton2 = Singleton.getInstance();
System.out.println(singleton1==singleton2);
}
执行结果为:true /*说明我们再次拿到的都是同一个对象*/
第二种:带有同步锁模式(synchronized)
单例设计模式代码二:
/***
* 单例设计模式synchronized方法
*/
public class Singleton {
//创建一个全局静态变量用来存放实例对象
private static Singleton instance;
//私有化构造方法,防止外界创建对象
private Singleton(){}
//对外界暴露获得实例对象的方法
public static synchronized Singleton getInstance(){
//判断是对象是否为空,
if (instance == null){
//为空则创建
return instance = new Singleton();
}
//不为空则直接返回
return instance;
}
}
/*同步代码块*/
public class Singleton {
//创建一个全局静态变量用来存放实例对象
private static Singleton instance;
//私有化构造方法,防止外界创建对象
private Singleton(){}
//对外界暴露获得实例对象的方法
public static Singleton getInstance(){
//判断是对象是否为空,
synchronized (Singleton.class){
if (instance == null){
//为空则创建
return instance = new Singleton();
}
}
//不为空则直接返回
return instance;
}
}
第三种:双重锁
package com.hn.singleton;
/***
* 单例设计模式
*/
public class Singleton {
//创建一个全局静态变量用来存放实例对象
private static Singleton instance;
//私有化构造方法,防止外界创建对象
private Singleton(){}
//对外界暴露获得实例对象的方法
public static Singleton getInstance(){
//判断是对象是否为空,
if (instance == null){
synchronized (Singleton.class){
if (instance == null){
//为空则创建
return instance = new Singleton();
}
}
}
//不为空则直接返回
return instance;
}
}
测试代码:
@Test
public void testDemo1() throws InterruptedException {
new Thread(() -> {
Singleton instance = Singleton.getInstance();
Singleton instance1 = Singleton.getInstance();
System.out.println("instance" + instance);
System.out.println("instance1" + instance1);
}).start();
new Thread(() -> {
Singleton instance2 = Singleton.getInstance();
Singleton instance3 = Singleton.getInstance();
System.out.println("instance2" + instance2);
System.out.println("instance3" + instance3);
}).start();
Thread.sleep(1000);
}
后期遇到会继续更新!