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

    单例模式有饿汉模式和懒汉模式两种实现。

    1.饿汉模式

    饿汉模式下,在类加载的时候,就创建了实例。

    特点是加载类时比较慢,但运行获取对象的速度比较快。并且是线性安全的。

    class Singleton{
        //1.将构造方法私有化,不允许外部直接创建对象
        private Singleton(){ }
        //2.创建类的唯一实例
        private static Singleton instance = new Singleton();
        //3.提供一个用于获取实例的方法
        public static Singleton getInstance(){
            return instance;
        }
    }
    public class Test {
        public static void main(String[] args) {
            Singleton s1 = Singleton.getInstance();
            Singleton s2 = Singleton.getInstance();
            if(s1 == s2){
                System.out.println("s1和s2是同一个实例");//输出这个
            }else {
                System.out.println("s1和s2不是同一个实例");
            }
        }
    }

     2.懒汉模式

    懒汉模式下,类加载时没创建实例,到了第一次获取实例的时候才创建。

    特点是加载类时比较快,但运行时获取对象的速度比较慢,是线程不安全的。

    class Singleton{
        //1.将构造方法私有化,不允许外部直接创建对象
        private Singleton(){ }
        //2.声明类的唯一实例
        private static Singleton instance ;
        //3.提供一个用于获取实例的方法
        public static Singleton getInstance(){
            if(instance == null){
                instance = new Singleton();
            }
            return instance;
        }
    }
    public class Test {
        public static void main(String[] args) {
            Singleton s1 = Singleton.getInstance();
            Singleton s2 = Singleton.getInstance();
            if(s1 == s2){
                System.out.println("s1和s2是同一个实例");//输出这个
            }else {
                System.out.println("s1和s2不是同一个实例");
            }
        }
    }
  • 相关阅读:
    three.js 显示中文字体 和 tween应用
    Caddy v1 版本增加插件
    Git 常用命令大全
    批量部署ssh免密登陆
    Python MySQLdb 模块使用方法
    python XlsxWriter创建Excel 表格
    DB2数据库的日志文件管理
    Linux 文本对比 diff 命令详解(整理)
    ssh 免交互登录 ,远程执行命令脚本。
    linux 出错 “INFO: task xxxxxx: 634 blocked for more than 120 seconds.”的3种解决方案(转)
  • 原文地址:https://www.cnblogs.com/ldn1230/p/10909157.html
Copyright © 2011-2022 走看看