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("不同一实例"); } } }
感谢您的阅读,您的支持是我写博客动力。