?單例保證一個對象JVM中只能有一個實例,常見單例 懶漢式、餓漢式
懶漢式
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;
}
}
第二種寫法,這種效率比上面這種高
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;
}
}