Skip to content

Commit

Permalink
add singleton design pattern
Browse files Browse the repository at this point in the history
  • Loading branch information
栗昭然 authored and 栗昭然 committed Apr 13, 2023
1 parent 7c91b47 commit fc91b27
Show file tree
Hide file tree
Showing 2 changed files with 114 additions and 2 deletions.
2 changes: 0 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,5 +41,3 @@ if (1 ^ n == n + 1) {
```
---

版权声明:本文为CSDN博主「wenyixicodedog」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/wenyiCodeDog/article/details/105525681
114 changes: 114 additions & 0 deletions src/main/java/org/example/SingletonClass.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
package org.example;

/**
* 7种单例设计模式
* 1.饿汉式
* 2.懒汉式
* 3.懒汉式+同步方法
* 4.Double check
* 5.Holder 方式
* 6.Enum 方式
* 7.Enum Holder
*/
public class SingletonClass {
//懒汉式单例
public static class StarvingSingleton {
private static final StarvingSingleton INSTANCE = new StarvingSingleton();

private StarvingSingleton(){}

public static StarvingSingleton getInstance(){
return INSTANCE;
}
}

//懒汉式单例
public static class LazyBoneSingleton{
private static LazyBoneSingleton INSTANCE;

private LazyBoneSingleton(){}

public static LazyBoneSingleton getInstance(){
if (INSTANCE == null){
INSTANCE = new LazyBoneSingleton();
}
return INSTANCE;
}
}

//懒汉式单例+同步方法
public static class LazyBoneSynchronizedSingleton{
private static LazyBoneSynchronizedSingleton INSTANCE;

private LazyBoneSynchronizedSingleton(){}

public static synchronized LazyBoneSynchronizedSingleton getInstance(){
if (null == INSTANCE){
INSTANCE = new LazyBoneSynchronizedSingleton();
}
return INSTANCE;
}
}

//Double-check
public static class DoubleCheckSingleton{
private volatile static DoubleCheckSingleton INSTANCE ;

private DoubleCheckSingleton(){}

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

//Holder
public static class HolderSingleton{
private HolderSingleton(){}

private static class Holder{
private static HolderSingleton instance = new HolderSingleton();

public static HolderSingleton getInstance(){
return Holder.instance;
}
}
}

//Enum
public enum EnumSingleton{
INSTANCE;

public static EnumSingleton getInstance(){
return INSTANCE;
}
}

//Enum Holder
public static class EnumHolderSingleton{
private EnumHolderSingleton(){}

private enum EnumHolder{
INSTANCE;
private EnumHolderSingleton instance;

EnumHolder(){
this.instance = new EnumHolderSingleton();
}

private EnumHolderSingleton getInstance(){
return instance;
}
}

public static EnumHolderSingleton getInstance(){
return EnumHolder.INSTANCE.getInstance();
}
}
}

0 comments on commit fc91b27

Please sign in to comment.