单利模式
程序员文章站
2022-07-04 08:44:48
...
public class Stinglegon2 {
//懒汉模式
private Stinglegon2(){
}
private static Stinglegon2 stinglegon2=null;
public static Stinglegon2 getstinglegon(){
if(stinglegon2==null){
return stinglegon2=new Stinglegon2();
}else{
return stinglegon2;
}
}
}
public class Stinglegon {
//饿汉模式
private Stinglegon(){//构造方法私有
}
private static final Stinglegon stinglegon=new Stinglegon();//又因为静态只能调静态,所以要加static。final修饰成员为常量
public static synchronized Stinglegon getStinglegon(){//因为构造方法被私有不能new对象,所以就用静态类名.方法。
return stinglegon;
}
}
测试
public class TextDemo {
public static void main(String[] args) {
Stinglegon s1=Stinglegon.getStinglegon();
Stinglegon s2=Stinglegon.getStinglegon();
boolean a=s1.equals(s2);
System.out.println(a);
System.out.println(s1==s2);
System.out.println("-----------------");
Stinglegon2 ss1=Stinglegon2.getstinglegon();
Stinglegon2 ss2=Stinglegon2.getstinglegon();
boolean aa=ss1.equals(ss2);
System.out.println(aa);
System.out.println(ss1==ss2);
}
}
结果
true
true
true
true