https://gist.github.com/opoo/e48dbc0b3c5d0afddfc0
好吧,github gist 貌似暂时不能访问了,贴在下面。
public class SingletonDemo {
public static class Singleton1{
private static final Singleton1 instance = new Singleton1();
private Singleton1(){}
public static Singleton1 getInstance(){
return instance;
}
}
public static class Singleton2{
private static Singleton2 instance;
private Singleton2(){};
public static synchronized Singleton2 getInstance(){
if(instance == null){
instance = new Singleton2();
}
return instance;
}
}
public static class Singleton3{
private static volatile Singleton3 instance;
private Singleton3(){}
public static Singleton3 getInstance(){
if(instance == null){
synchronized (Singleton3.class){
if(instance == null){
instance = new Singleton3();
}
}
}
return instance;
}
}
public static class Singleton4{
private static final Singleton4 instance;
static{
instance = new Singleton4();
}
private Singleton4(){}
public static Singleton4 getInstance(){
return instance;
}
}
public static class Singleton5{
private static class SingletonHolder{
private static final Singleton5 instance = new Singleton5();
}
private Singleton5(){}
public static Singleton5 getInstance(){
return SingletonHolder.instance;
}
}
}
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.