基于SnapDragonBoard410c的单例设计模式

单例模式是设计模式中最常见也最简单的一种设计模式,保证了在程序中只有一个实例存在并且能全局的访问到。下面针对一些例子分析一下我们在开发过程中应用单例模式需要注意的点。

单例模式(Singleton):保证一个类仅有一个实例,并提供一个访问它的全局访问点。
1. 应用中某个实例对象需要频繁的被访问。
2. 应用中每次启动只会存在一个实例。如账号系统,数据库系统。

(一)懒汉式 (这种方式创建单例,在使用多线程的情况下可能是线程不安全的主要因素。)

public class Singleton {
    /* 持有私有静态实例,防止被引用,此处赋值为null,目的是实现延迟加载 */
    private static Singleton instance = null;
    /* 私有构造方法,防止被实例化 */
    private Singleton() {
    }
    /* 1:懒汉式,静态工程方法,创建实例 */
    public static Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}

(2)解决线程不安全的普通方法

/*2.懒汉式,解决线程安全问题**/  
 public static synchronized Singleton getInstance() {  
     if (instance == null) {  
         instance = new Singleton();  
     }  
     return instance;  
 }  

或者如下:

/*加上synchronized,但是每次调用实例时都会加载**/  
 public static Singleton getInstance() {  
     synchronized (Singleton.class) {  
         if (instance == null) {  
             instance = new Singleton();  
         }  
     }  
     return instance;  
 }

(二)内部类的实现
内部类是一种好的实现方式,可以推荐使用一下:

public class SingletonInner {  

    /** 
     * 内部类实现单例模式 
     * 延迟加载,减少内存开销 
     */  
    private static class SingletonHolder {  
        private static SingletonInner instance = new SingletonInner();  
    }  

    /** 
     * 私有的构造函数 
     */  
    private SingletonInner() {  

    }  

    public static SingletonInner getInstance() {  
        return SingletonHolder.instance;  
    }  

    protected void method() {  
        System.out.println("SingletonInner");  
    }  
}  

(三)枚举的方法

public class SingletonInner {  

    /** 
     * 内部类实现单例模式 
     * 延迟加载,减少内存开销   
     */  
    private static class SingletonHolder {  
        private static SingletonInner instance = new SingletonInner();  
    }  
    /** 
     * 私有的构造函数 
     */  
    private SingletonInner() {  

    }  
    public static SingletonInner getInstance() {  
        return SingletonHolder.instance;  
    }  
    protected void method() {  
        System.out.println("SingletonInner");  
    }  
}  

猜你喜欢

转载自blog.csdn.net/u013763766/article/details/79276851