zoukankan      html  css  js  c++  java
  • 单利设计模式

    单利设计模式:饿汉模式,懒汉模式

    应用场合:有些对象只需要一个就足够了,如古代的皇帝,老婆

    作用:保证整个应用程序中某个实例有且只有一个

     

    区别:饿汉模式加载类时候比较慢,但在运行时获得对象的速度比较快,线程比较安全

    懒汉模式加载类的时候比较快,但是在运行时获得对象的速度比较慢,线程不安

    简单来说:饿汉是用空间换时间,懒汉就是用时间换空间

    Singleton:

    package com.imo;
    
    public class Singleton {
        //1.将构造方法私有化,不允许外部创建对象
        private Singleton(){
            
        }
        
        //2.创建类的唯一实例,使用private static 修饰
        private static Singleton instance = new Singleton();
        
        //3.提供一个用于获取实例的方法,使用public static 修饰
        public static Singleton getInstance(){
            return instance;
        }
    
    }

    Singleton2:

    package com.imo;
    
    public class Singleton2 {
        //1.构造函数私有化,不允许外部创建对象
        private Singleton2(){
            
        }
    
        //2.创建类的唯一实例,并用private static修饰
        private static Singleton2 instance;
        
        //3.提供一个获取实例的方法,用public static 修饰
        public static Singleton2 getInstance(){
            if(instance==null){
                instance = new Singleton2();
            }
            return instance;
        }
    
        
    }

    Test:

    package com.imo;
    
    public class Test {
    
        /**
         * @param args
         */
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            //饿汉模式
            Singleton s1 = Singleton.getInstance();
            Singleton s2 = Singleton.getInstance();
            if(s1==s2){
                System.out.println("s1和s2是同一个实例");
            }else{
                System.out.println("s1和s2不是同一个实例");
            }
            
            //懒汉模式
            Singleton2 s3 = Singleton2.getInstance();
            Singleton2 s4 = Singleton2.getInstance();
            if(s3==s4){
                System.out.println("s1和s2是同一个实例");
            }else{
                System.out.println("s1和s2不是同一个实例");
            }
            
        }
    
    }
  • 相关阅读:
    CentOS7 安装 RabbitMQ
    测试工程师 - 要了解的技能总结
    STF 连接其它操作系统上的安卓设备实操介绍【转】
    adb -a server nodaemon,设备一直显示 offline,而 adb devices 一直显示 device【已解决】
    Mac 之 STF 搭建(淘宝源安装)
    无损压缩图片
    jenkins 之 Android 打包及上传至蒲公英
    JoinPoint
    元数据库 information_schema.tables
    @RestControllerAdvice全局异常统一处理
  • 原文地址:https://www.cnblogs.com/sunxiaoyan/p/8874611.html
Copyright © 2011-2022 走看看