java单例模式

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

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("不同一实例");
        }
    }
}

 

posted @ 2017-02-13 11:39  N神3  阅读(188)  评论(0编辑  收藏  举报