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

    设计模式

    单例模式

    懒汉模式

    class Person{
        /**
         * 单例模式设计
         */
    
        private String name;
        private int age;
        // 类字段
    
        private static Person person = null;
        // 定义一个私有变量以提供唯一实例
    
        private Person(){
        }
        // 私有化构造方法
    
        /**
         * 由于可能会有多线程访问,所以要锁
         * @return Person的唯一实例
         */
        public static synchronized Person getInstance(){
            if (person == null){
                person = new Person();
            }
    
            return person;
        }
    
        /**
         * 换个锁的位置保证效率
         * @return person的唯一实例
         */
        public static Person getInstance2(){
            if (person == null){
                synchronized (Person.class){
                    if (person == null) {
                        person = new Person();
                    }
                }
            }
            return person;
        }
    }
    

    饿汉模式

    class Student{
        private static final Student STUDENT = new Student();
        // 预实例化变量保存起来
    
        private Student() {
    
        }
        // 私有化构造方法
    
        /**
         * 直接返回,只读不需要考虑锁的问你
         * @return Student的唯一实例
         */
        public static Student getInstance(){
            return STUDENT;
        }
    
    }
    

    总结

    1. 懒汉模式更节省内存,但是反之需要锁结构,会影响第一次访问时的效率
  • 相关阅读:
    在Js或者cess后加版本号 防止浏览器缓存
    svn操作
    Hash表
    网站js埋点
    c#优秀文章
    CentOS修改默认yum源为国内yum镜像源
    mysql开启远程连接
    安装jdk环境
    Eclipse的一下设置
    好用的在线HTML、CSS工具
  • 原文地址:https://www.cnblogs.com/rainful/p/15022071.html
Copyright © 2011-2022 走看看