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;
        }
    }
    
  • 相关阅读:
    Leetcode 16.25 LRU缓存 哈希表与双向链表的组合
    Leetcode437 路径总和 III 双递归与前缀和
    leetcode 0404 二叉树检查平衡性 DFS
    Leetcode 1219 黄金矿工 暴力回溯
    Leetcode1218 最长定差子序列 哈希表优化DP
    Leetcode 91 解码方法
    Leetcode 129 求根到叶子节点数字之和 DFS优化
    Leetcode 125 验证回文串 双指针
    Docker安装Mysql记录
    vmware虚拟机---Liunx配置静态IP
  • 原文地址:https://www.cnblogs.com/TCB-Java/p/6770128.html
Copyright © 2011-2022 走看看