欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

单例模式讲解

程序员文章站 2022-05-15 10:58:55
...

Singleton类之所以是private型构造方法,就是为了防止其它类通过new来创建实例,即如此,那我们就必须用一个static的方法来创建一个实例(为什么要用static的方法?因为既然其它类不能通过new来创建实例,那么就无法获取其对象,那么只用有类的方法来获取了)

 class Singleton {   
 
      private static Singleton instance;  
 
      private static String str="单例模式原版" ;
 
  
 
      private Singleton(){}   

     public static Singleton getInstance(){   

         if(instance==null){   

             instance = new Singleton();   

         }   

         return instance;   

     }   

     public void say(){   

         System.out.println(str);   

     }  

     public void updatesay(String i){

           this.str=i;

           

          

     } 

}   

  

public class danli{   

    public static void main(String[] args) {   

        Singleton s1 = Singleton.getInstance();   

        //再次getInstance()的时候,instance已经被实例化了   
        //所以不会再new,即s2指向刚初始化的实例   
        Singleton s2 = Singleton.getInstance();   

        System.out.println(s1==s2);   

        s1.say();   

        s2.say();   

        //保证了Singleton的实例被引用的都是同一个,改变一个引用,则另外一个也会变.

        //例如以下用s1修改一下say的内容

        s1.updatesay("hey is me Senngr");   

        s1.say();  

        s2.say(); 

        System.out.println(s1==s2); 
    }   

}

 

 打印结果:

true

单例模式原版

单例模式原版

hey is me Senngr

hey is me Senngr

true

 

private static Singleton instance;
public static Singleton getInstance()
这2个是静态的 

1.定义变量的时候是私有,静态的:private static Singleton instance;
2.定义私有的构造方法,以防止其它类通过new来创建实例;
3.定义静态的方法public static Singleton getInstance()来获取对象.instance = new Singleton();

相关标签: j2ee