- class Single
- {
- int num;
- private static Single s = null;
- private Single(int num){
- this.num = num;
- }
- public static Single getInstance(int num)
- {
- while(s==null){//这行代码必须要加上才能实现单例
- s=new Single(num);
- }
- return s;
- }
- }
- public class SingleDemo
- {
- public static void main(String[] args)
- {
- Single s1=Single.getInstance(1);
- Single s2=Single.getInstance(2);
- System.out.println(s1==s2);//true,说明是同一个对象,还是单例设计模式
- System.out.println("s1="+s1.num);//1
- System.out.println("s2="+s2.num);//1
- System.out.println("s1="+s1.num);//1
- }
- }
复制代码 |