单例模式的特点:解决了一个类在内存的唯一性,这个类的对象只有一个。
写单例模式的步骤:
1. 私有修饰构造方法
2. 在本类的成员位置, new 自己类的对象
3. 提供一个静态方法,返回本类的对象
A: 恶汉式
package demo01;
/**
* 单例设计模式恶汉式
* @author Administrator
*
*/
public class SingleDesignModel1 {
//私有构造方法
private SingleDesignModel1(){
}
//在自己的成员变量的位置,new 自己
private static final SingleDesignModel1 singleDesignModel1=new SingleDesignModel1();
//提供一个静态方法,返回一个本类对象
public static SingleDesignModel1 getInstance(){
return singleDesignModel1;
}
}
B:懒汉式
package demo01;
/**
* 单例模式的懒汉式
* @author Administrator
*
*/
public class SingleDesignModel2 {
private static SingleDesignModel2 singleDesignModel2=null;
private SingleDesignModel2(){
}
public static SingleDesignModel2 getInstance(){
if(singleDesignModel2==null){
singleDesignModel2=new SingleDesignModel2();
}
return singleDesignModel2;
}
}
单例模式的运行原理: