zoukankan      html  css  js  c++  java
  • Java中设计模式之单例设计模式-1

    单例作用

    • 1 节省内存
    • 2 可以避免多种状态导致状态冲突

    单例的创建步骤

    • 1 私有化构造方法
    • 2 私有化声明的属性
    • 3 getInstance
    • 4 方法需要静态

    单例分类

    1.懒汉式
    2.饿汉式

    两种单例区别:

    饿汉式 线程安全的
    懒汉式 线程不安全的

    饿汉式:

    package 设计模式之单例;
    //饿汉式:
    public class HungeryMode {
        private final static HungeryMode INSTANCE=new HungeryMode();
    
        public static HungeryMode getInstance() {
            return INSTANCE;
        }
        private HungeryMode(){}
    
    }
    

    懒汉式:

    package 设计模式之单例;
    
    public class LazyMode {
        private static LazyMode instance=null;
    
        public static LazyMode getInstance() {
            if(instance==null){
                instance=new LazyMode();
            }
    
            return instance;
        }
    
        private LazyMode(){}
    }
    

    测试:

    package 设计模式之单例;
    
    public class Test1 {
        public static void main(String[] args){
            //饿汉式  
            HungeryMode instance=HungeryMode.getInstance();
            HungeryMode instance2=HungeryMode.getInstance();
            System.out.println("instance="+instance);
            System.out.println("instance2="+instance2);
    
            // 懒汉式
            LazyMode instance3=LazyMode.getInstance();
            LazyMode instance4=LazyMode.getInstance();
            LazyMode instance5=LazyMode.getInstance();
            System.out.println("instance3="+instance3+","+instance3.hashCode());
            System.out.println("instance4="+instance4+","+instance4.hashCode());
            System.out.println("instance5="+instance5+","+instance5.hashCode());
    
        }
    }
    

    测试结果:
    这里写图片描述

    创建多个对象,测试内存地址,如果相同说明创建的是同一个对象,说明创建的是单例!

    延伸—————————–懒汉式线程安全性处理————————–

    懒汉式线程不安全原因:

    在多线程中,创建单例时,可能出现多个线程进入if(instance==null)执行语句中,在一个线程创建了一个instance后,其他进入执行语句的线程也会接着创建,这样就会产生多个对象,实现不了单例了,此时不安全了。

    代码:

    package 设计模式之单例;
    
    public class LazyMode2 {
        private static LazyMode2 instance=null;
        private LazyMode2(){}
        public static LazyMode2 getInstance(){
            // 双重检查
            if(instance==null){// 为了提高效率   尽可能少的让线程反复判断锁
                synchronized (LazyMode2.class) {// 静态方法中 不能使用this 就可以用 本类.class 来代替
                    if(instance==null){
                        instance=new LazyMode2();
                    }
                }
            }
            return instance;
        }
    }
    
  • 相关阅读:
    ng-class中的if else判断
    Sass 的使用
    pre 标签的使用
    C++操作 SQL数据库 实例 代码步骤
    自己写的一个操作Mysql的简单的实例
    C++ 链接Mysql 函数介绍
    Mysql 操作命令 详解
    MFC程序开始的执行过程详述
    Java各种日期格式的获取和设置指定日期
    DM8168 OpenCV尝试与评估(编译ARM版OpenCV)
  • 原文地址:https://www.cnblogs.com/TCB-Java/p/6770128.html
Copyright © 2011-2022 走看看