设计模式-单例模式实现过程案例

设计思路:1.创建静态私有对象;2.构造方法私有化;3.静态公有的对象地址方法

 

一.

/**
* @author jiagx
* @description 单例模式-线程不安全版本
* @date 2020/5/27 9:54
*/
public class Singleton {

private static Singleton singleton;

private Singleton(){
};

public static Singleton getInstance(){
if (singleton==null){
singleton=new Singleton();
}
return singleton;
}

}


二.
/**
* @author jiagx
* @description 单例模式-同步锁单例模式
* @date 2020/5/27 9:58
*/
public class SingletonSyn {
private static SingletonSyn singleton;

private SingletonSyn(){};

public static synchronized SingletonSyn getInstance(){
synchronized (SingletonSyn.class){
if (singleton==null){
singleton=new SingletonSyn();
}
}
return singleton;
}
}


三.
/**
* @author jiagx
* @description 单例模式-双层校验锁机制的同步锁单例模式
* @date 2020/5/27 10:12
*/
public class SingletonSyn2 {

private static SingletonSyn2 singletonSyn2;

private SingletonSyn2(){

}


public static synchronized SingletonSyn2 getInstance(){

if (singletonSyn2==null){
synchronized (SingletonSyn2.class){
if (singletonSyn2==null){
singletonSyn2=new SingletonSyn2();
}
}
}
return singletonSyn2;
}
}


四.
/**
* @author jiagx
* @description 单例模式-无锁线程安全单例模式,最优秀的单例模式
* @date 2020/5/27 10:38
*/
public class SingletonSynNoLock {

private final static SingletonSynNoLock singletonSynNoLock = new SingletonSynNoLock();

private SingletonSynNoLock(){};

@Synchronized
public static SingletonSynNoLock getInstance(){
return singletonSynNoLock;
}

}

posted on 2020-05-27 10:50  贾广祥  阅读(371)  评论(0编辑  收藏  举报

导航