码迷,mamicode.com
首页 > 其他好文 > 详细

单例模式

时间:2016-10-14 23:13:34      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:

一、单例模式之饿汉模式

 

package com.singleton;

public class SingletonHungry {

    private static SingletonHungry singletonHungry = new SingletonHungry();
    
    private SingletonHungry() {}
    
    public static SingletonHungry getInstance() {
        
        return singletonHungry;
    }
    
    
    
    
    
}

 

二、懒汉模式

package com.singleton;

public class SingletonLazy {
    
    private static SingletonLazy singletonLazy;
    
    private SingletonLazy() {}
    
    
    public synchronized static SingletonLazy getInstance() {
        
        if(singletonLazy == null) {
            
            singletonLazy = new SingletonLazy();
        }
        
        return singletonLazy;
        
    }

}

三、测试

package com.singleton;

public class Test {
    
    public static void main(String[] args) {
        
        SingletonHungry singletonHungry1 = SingletonHungry.getInstance();
        SingletonHungry singletonHungry2 = SingletonHungry.getInstance();
        
        System.out.println(singletonHungry1 == singletonHungry2);
        
        
        SingletonLazy singletonLazy1 = SingletonLazy.getInstance();
        SingletonLazy singletonLazy2 = SingletonLazy.getInstance();
        
        System.out.println(singletonLazy1 == singletonLazy2);
        
    }

}

四、结果

true

true

 

单例模式

标签:

原文地址:http://www.cnblogs.com/honger/p/5961994.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!