单例模式——懒汉模式和饿汉模式

步骤:

1、私有化构造函数

2、在本类中创建一个本类对象

3、定义一个公有方法,将创建的对象返回

public class Test18 {

	public static void main(String[] args) {
		Single1 s1=Single1.getSingle1();
	}

}
/**
 * 饿汉模式
 */
class Single1{
	private  Single1(){};
	private static Single1 s1=new Single1();
	public static Single1 getSingle1(){
		return s1;
	}
}
/**
 * 懒汉模式
 */
class Single2{
	private Single2(){};
	private static Single2 s2=null;
	public static Single2 getSingle2(){
		if(s2==null){
			s2=new Single2();
		}
		return s2;
	}
}


你可能感兴趣的:(JAVA)