java单例模式实现

 

1.最基本的单例模式

复制代码
/**  * @author LearnAndGet  * @time 2018年11月13日  *  最基本的单例模式  */public class SingletonV1 {          private static SingletonV1 instance = new SingletonV1();;          //构造函数私有化    private SingletonV1() {}      public static SingletonV1 getInstance()      {         return instance;     } }
复制代码
复制代码
import org.junit.Test; public class SingletonTest {          @Test     public void test01() throws Exception     {         SingletonV1 s1 = SingletonV1.getInstance();         SingletonV1 s2 = SingletonV1.getInstance();         System.out.println(s1.hashCode());         System.out.println(s2.hashCode());     } }  //运行结果如下:589873731589873731
复制代码

2.类加载时不初始化实例的模式

  上述单例模式在类加载的时候,就会生成实例,可能造成空间浪费,如果需要修改成,在需要使用时才生成实例,则可修改代码如下:

复制代码
 1 public class SingletonV2 {  2      3     private static SingletonV2 instance;  4      5     //构造函数私有化 6     private SingletonV2() {}  7  8     public static SingletonV2 getInstance(){ 10         if(instance == null)  11         { 12             instance = new SingletonV2(); 13         } 14         return instance; 15     } 
                        
关键字:
50000+
5万行代码练就真实本领
17年
创办于2008年老牌培训机构
1000+
合作企业
98%
就业率

联系我们

电话咨询

0532-85025005

扫码添加微信