单利模式
程序员文章站
2022-07-04 08:44:00
...
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;
}
}
转载于:https://www.jianshu.com/p/0dffbcb97d44
上一篇: Linq查询
下一篇: Spring加载properties文件