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

    单例模式:一个类只保留一个实例,通过私有化构造器,然后在本类中创建一个公共的静态的获取实例的方法,外部就可以通过类名.方法的形式获得该类的实例;
    当多线程情况下,线程获得时间片短路,容易创建多个实例,所以采用一个锁机制解决。

    public
    class Singleton { private static Singleton instance = new Singleton(); //先创对象 ,饿汉式 private Singleton() { } public static Singleton getInstance(){ return instance; } }
    public class Singleton {  
        private static Singleton instance=null;  
         
        private Singleton() {  
             
        }  
         
        public static Singleton getInstance(){  
            if (instance == null) {  
                instance = new Singleton();    //调用方法再创对象,懒汉式
            }  
             
            return instance;  
        }  
    }

    为了应对多线程问题;采取一个加锁解决,把门关上,但是每次调用方法都会经过锁,会影响性能,所以在外面再加一个判断。

    synchronized同步块括号中的锁定对象是采用的一个无关的Object类实例,而不是采用this,因为getInstance是一个静态方法,在它内部不能使用未静态的或者未实例的类对象,

    public class Singleton {  
        private static Singleton instance;  
         
        private Singleton() {  
             
        }  
         
        public static Singleton getInstance(){  
            if (instance == null) {  //外层一个判断,再进入锁
                synchronized (Singleton.class) {  
                    if (instance == null) {  
                        instance = new Singleton();  
                    }  
                }  
            }  
             
            return instance;  
        }  
    }
  • 相关阅读:
    OC字符串处理
    用 map 表达互斥逻辑
    iOS之LLDB调试器
    iOS 线程安全 锁
    OC实现 单向链表
    iOS读取info.plist中的值
    SQLite 如何取出特定部分数据
    UIView常用的一些方法setNeedsDisplay和setNeedsLayout
    xCode常用快捷键
    oppo7.0系统手机(亲测有效)激活Xposed框架的流程
  • 原文地址:https://www.cnblogs.com/JavaBlackHole/p/7667465.html
Copyright © 2011-2022 走看看