zoukankan      html  css  js  c++  java
  • 单例

    单例设计模式,就是保证对象的实例只有一个,防止每个用这个对象的人都创建一个实例。

    私有化构造方法

    提供对象返回方法,用static修饰

    对象创建语句要是在外面,需要用 static final限定词

    1、饿汉:类加载时就先把对象实例准备好。

    public class SingleTon {
    
        private SingleTon(){}
    
        private static final Peopel peopel=new Peopel();
    
        public static Peopel getInstance(){
            return peopel;
        }
    
    }

    2、懒汉:什么时候要对象,什么时候再去创建。但是要记得加判断,即,实例为空的时候才去创建,不为空就返回,不加判断就是多例了。

    public class SingleTon {
    
        private static People people;

    private SingleTon(){} public static People getInstance(){ if(peopel==null){ people=new People(); } return people; } }

    3、多线程下的单例:线程安全

    public class SingleTon {
    
        private volatile static People people;
        private SingleTon(){}
    
        public static People getInstance(){
            if(peopel==null) {
                //孩子没产生,大家进去排队,抢着造人
                synchronized (People.class) {
                    if (peopel == null) {
                        people = new People();
                    }
                }
            }
            //孩子产生了那就不用都排队了,就去要孩子就好了
            return people;
        }
    
    }
    public class Singleton {
    
        private volatile static Singleton uniqueInstance;
    
        private Singleton() {
        }
    
        public static Singleton getUniqueInstance() {
           //先判断对象是否已经实例过,没有实例化过才进入加锁代码
            if (uniqueInstance == null) {
                //类对象加锁
                synchronized (Singleton.class) {
                    if (uniqueInstance == null) {
                        uniqueInstance = new Singleton();
                    }
                }
            }
            return uniqueInstance;
        }
    }
  • 相关阅读:
    oc中 中文到拼音的转换
    ios 添加全屏返回手势
    自我总结- CGAffineTransform
    解决pod search出来的库不是最新
    四舍五入的函数,保留小数点后几位数不四舍五入
    iOS 键盘变中文
    LanguageImage尺寸
    打包上传64位支持的解决办法
    第1年11月2日 ssh分发秘钥时出现错误“Permission denied (publickey,gssapi-keyex,gssapi-with-mic)” yarn
    第1年11月1日 uniapp原生
  • 原文地址:https://www.cnblogs.com/guoyu1/p/12000584.html
Copyright © 2011-2022 走看看