zoukankan      html  css  js  c++  java
  • 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("不同一实例");
            }
        }
    }
  • 相关阅读:
    快速模幂
    UPC-2249 曲线分割【递推】
    maven 服务器
    maven repo
    php-fpm sock
    mysql
    go 1
    xdebug
    centos
    win10 2503 2502
  • 原文地址:https://www.cnblogs.com/chenweichu/p/6393104.html
Copyright © 2011-2022 走看看