?單例保證一個(gè)對(duì)象JVM中只能有一個(gè)實(shí)例,常見(jiàn)單例 懶漢式、餓漢式
懶漢式
public class Person{
private static Person person;
private Person() {
}
public static Person getPerson() {
if(person==null) {
return new Person();
}
return person;
}
}
惡漢式
public class Person{
private static final Person person=new Person();
private Person() {
}
public static Person getPerson() {
return person;
}
懶漢式線程不安全甘耿,若想要線程安全可以改為(加synchronized?)
public class Person{
private static Person person;
private Person() {
}
public static synchronized Person getPerson() {
if(person==null) {
return new Person();
}
return person;
}
}
第二種寫(xiě)法浩姥,這種效率比上面這種高
public class Person{
private static Person person;
private Person() {
}
public static Person getPerson() {
if(person==null) {
synchronized (Person.class) {
if(person==null) {
return new Person();
}
}
}
return person;
}
}