2018-10-26 看懂单例
2018-10-26 本文已影响0人
江江江123
//懒汉式单例
public class SingleTwo {
private SingleTwo() {
}
private static SingleTwo singleTwo = null;
public static SingleTwo getSingleTwo() {
if (singleTwo == null) {
singleTwo = new SingleTwo();
}
return singleTwo;
}
}
//饿汉式单例
public class Single {
private Single() {
}
private static Single single = new Single();
public static Single getSingle(){
return single;
}
public static void main(String[] args) {
//单例与非单例的区别
StringBuffer stringBuffer = new StringBuffer();
StringBuffer stringBuffer1 = new StringBuffer();
System.out.println(stringBuffer.equals(stringBuffer1));//false
Single single = Single.getSingle();
Single single1 = Single.getSingle();
System.out.println(single.equals(single1));//true
SingleTwo singleTwo = SingleTwo.getSingleTwo();
SingleTwo singleTwo1 = SingleTwo.getSingleTwo();
System.out.println(singleTwo.equals(singleTwo1));//true
//单例可以保证我们总是在操作同一个对象
}
}