代码一:
class Single
{
private Single(){}
private static Single s = new Single();
private static Single getInstance()
{
return s;
}
}
特点:先初始化对象,即Single类一进内存,就已经创建好了对象
被称为:饿汉式
代码二:
class Single
{
private Single(){}
private static Single s = null;
private static synchronized Single getInstance()
{
if(s == null)
s = new Single();
class Demo1 {
public static void main(String[] args) {
ton t1 = ton.getTon();
ton t2 = ton.getTon();
System.out.println(t1 == t2);
tontwo tt1 = tontwo.getTontwo();
tontwo tt2 = tontwo.getTontwo();
System.out.println(tt1 == tt2);
}
}
//饿汉式
class ton {
private static ton t = new ton();
private ton() {}
public static ton getTon() {
return t;
}
}
//懒汉是
class tontwo {
private static tontwo t;
private tontwo() {}
public static tontwo getTontwo() {
if (t == null) {
new tontwo();
}
return t;
}
}
//执行结果