实现单例模式的8种方式
Posted 程序员Club
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了实现单例模式的8种方式相关的知识,希望对你有一定的参考价值。
public class Singleton01 {
private static Singleton01 instance = new Singleton01();
private Singleton01(){
}
public static Singleton01 getInstance(){
return instance;
}
}
public class Singleton02 {
private static Singleton02 instance ;
static {
instance = new Singleton02();
}
private Singleton02(){
}
public static Singleton02 getInstance(){
return instance;
}
}
public class Singleton03 {
private static Singleton03 instance ;
private Singleton03(){
}
public static Singleton03 getInstance(){
if(null !=instance){
instance = new Singleton03();
}
return instance;
}
}
public class Singleton04 {
private static Singleton04 instance ;
private Singleton04(){
}
public static synchronized Singleton04 getInstance(){
if(null !=instance){
instance = new Singleton04();
}
return instance;
}
}
public class Singleton05 {
private static Singleton05 instance ;
private Singleton05(){
}
public static Singleton05 getInstance(){
if(null !=instance){
synchronized (Singleton05.class){
instance = new Singleton05();
}
}
return instance;
}
}
public class Singleton06 {
private static Singleton06 instance ;
private Singleton06(){
}
public static Singleton06 getInstance(){
if(null !=instance){
synchronized (Singleton06.class){
if(instance !=null){
instance = new Singleton06();
}
}
}
return instance;
}
}
public class Singleton07 {
private Singleton07(){
}
private static class SingletonInstance{
private static Singleton07 instance = new Singleton07();
}
public static Singleton07 getInstance() {
return SingletonInstance.instance;
}
}
public enum Singleton08 {
INSTANCE;
public void whateverMethod(){
}
}
以上是关于实现单例模式的8种方式的主要内容,如果未能解决你的问题,请参考以下文章