1、饿汉式
package com.company;
/**
* 饿汉式
* Created by dra on 2017/7/7.
*/
public class Person {
private String name;
private static final Person PERSON = new Person();
private Person(){}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
/**
* 获取单利
* @return
*/
public static Person getPerson(){
return PERSON;
}
}
2、懒汉式
package com.company;
/**
* 懒汉式
* Created by dra on 2017/7/7.
*/
public class Person2 {
private String name;
private static Person2 person;
private Person2(){}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
/**
* 获取单利
* @return
*/
public static Person2 getPerson(){
if (person == null){
person= new Person2();
}
return person;
}
}
3、双重检查
package com.company;
/**
* 双重检查
* Created by dra on 2017/7/7.
*/
public class Person2 {
private String name;
private static Person2 person;
private Person2(){}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
/**
* 获取单利
* @return
*/
public static Person2 getPerson(){
if (person== null){
synchronized (Person2.class){
if (person== null){
person= new Person2();
}
}
}
return person;
}
}