Skip to content

Instantly share code, notes, and snippets.

@liubin95
Created February 15, 2022 05:57
Show Gist options
  • Save liubin95/e38e02bb52078132ee57dfa33ae103a5 to your computer and use it in GitHub Desktop.
Save liubin95/e38e02bb52078132ee57dfa33ae103a5 to your computer and use it in GitHub Desktop.
单例模式
import java.util.stream.IntStream;
/**
* Singleton.
*
* @author 刘斌
* @version 0.0.1
* @serial 2022-02-15 : base version.
*/
public class Singleton {
public static void main(String[] args) {
IntStream.range(0, 10).forEach(i -> {
System.out.println(Load.getInstance());
System.out.println(LazyLoad.getInstance());
});
}
}
class Load {
private final static Load LOAD = new Load();
private Load() {
}
public static Load getInstance() {
return LOAD;
}
@Override
public boolean equals(Object obj) {
return super.equals(obj);
}
}
class LazyLoad {
private volatile static LazyLoad load = null;
private LazyLoad() {
}
public static LazyLoad getInstance() {
if (load == null) {
synchronized (LazyLoad.class) {
if (load == null) {
load = new LazyLoad();
}
}
}
return load;
}
@Override
public boolean equals(Object obj) {
return super.equals(obj);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment