首页 > 编程语言 > 详细

java单例模式

时间:2017-02-13 12:37:26      阅读:175      评论:0      收藏:0      [点我收藏+]

一、饿汉模式(实例早早在类加载时就创建)

public class TestPerson {private static TestPerson testPerson = new TestPerson();

private TestPerson(){

}

public static TestPerson getInstance(){
return testPerson;
}

}

二、懒汉模式

public class TestPerson {
    
    private static TestPerson testPerson;
    
    private TestPerson(){
        
    }
    
    public static TestPerson getInstance(){
        if(testPerson==null){
            testPerson = new TestPerson();
        }
        return testPerson;
    }

}

三、测试

public class Test {

    public static void main(String[] args) {
        TestPerson t1 = TestPerson.getInstance();
        TestPerson t2 = TestPerson.getInstance();
        if(t1==t2){
            System.out.println("同一实例");
        }else{
            System.out.println("不同一实例");
        }
    }
}

 

java单例模式

原文:http://www.cnblogs.com/chenweichu/p/6393104.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!