zoukankan      html  css  js  c++  java
  • 单例模式

    一、单例模式之饿汉模式

    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

  • 相关阅读:
    算法与数据结构9
    算法与数据结构8
    数据结构与算法7
    数据结构与算法6
    计算机视觉(七)
    计算机视觉(六)
    计算机视觉(五)
    vscode 创建java项目
    vue 访问API接口
    vscode+vue 框架搭建
  • 原文地址:https://www.cnblogs.com/honger/p/5961994.html
Copyright © 2011-2022 走看看