单例模式

来源:互联网 发布:淘宝介入的原则 编辑:程序博客网 时间:2024/06/16 15:23
单例模式:只能创建一个对象
* 饿汉式
* 1.私有构造方法
* 2.私有静态成员对象
* 3.创建公共公开方法返回静态私有对象
* @author liuxin
*
*/
public class Single1 {
private static Single1 s1=new Single1();
private Single1(){}
public static Single1 getInstance(){
return s1;
}
}
**
* 懒汉式(延时加载)
* 1.私有构造方法
* 2.私有静态成员对象
* 3.创建一个公共公开的静态方法返回私有对象
* @author liuxin
*
*/
public class Single2 {
private static Single2 s2=null;
private Single2(){}
public static Single2 getInstance(){
if(s2==null){
return s2=new Single2();
}
return s2;
}
}
0 0