单例设计模式
单例保证一个对象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;
}
}