1,饿汉式
- 私有对象
- 私有构造
- 公共对象实现方法
一般用于:重量级对象,工具类,数据源,session工厂等
假设这是一个重量对象:
public class heightObj {
private Integer age;
private String name;
@Override
public String toString() {
return "heightObj{" +
"age=" + age +
", name='" + name + '\'' +
'}';
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
饿汉式实现:
import cn.height.heightObj;
/**
* 单例设计模式第一种实现方式
* 饿汉式
*/
public class singleCase1 {
//1,私有对象
private static final heightObj ho=new heightObj();
//2,私有构造犯法
private singleCase1(){
}
//3,对外提供实现方法
public static heightObj getinstance(){
return ho;
}
}
懒汉式第一种,线程不安全
/**
* 线程不安全的
* 懒汉模式
*/
public class singleCase2 {
private static heightObj ho ;
private singleCase2(){
}
public static heightObj getinstance(){
if(ho==null){
ho=new heightObj();
}
return ho;
}
}
懒汉模式(线程安全):
/**
* 懒汉模式(线程安全)
*/
public class singleCase3 {
private static heightObj heightObj;
private singleCase3(){
}
public static synchronized heightObj getinstance(){
if(heightObj==null){
heightObj=new heightObj();
}
return heightObj;
}
}
双重检查模式 (DCL) 懒汉式延申:
/**
* 双重检查模式 (DCL)
* 懒汉式延申
*/
public class singleCase4 {
private static volatile heightObj heightObj;
private singleCase4(){}
public static heightObj getinstance(){
if(heightObj==null){
synchronized (singleCase4.class){
if (heightObj==null){
heightObj=new heightObj();
}
}
}
return heightObj;
}
}
使用静态内部类写单例:
/**
* 静态内部类使用
* 静态内部类在外部类加载时候不会加载
*/
public class singleCase5 {
private singleCase5(){}
private static class singleinnerCase5{
private static final heightObj heightObj =new heightObj();
}
public static heightObj getinstance(){
return singleinnerCase5.heightObj;
}
}