设计模式-单例

单例模式是一种常见的设计模式

单例模式有以下特点:

  1、单例类只能有一个实例。
  2、单例类必须自己创建自己的唯一实例。
  3、单例类必须给所有其他对象提供这一实例。

 

饿汉式单例

public class Singleton {

    private static Singleton instance = new Singleton();

    public static Singleton getInstance() {
        return instance;
    }
}

在类创建的同时就已经创建好一个静态的对象供系统使用,以后不再改变

 

懒汉式单例

public class Singleton {

    private static Singleton instance = null;

    /**
     * 懒汉模式一 
     * 同步方法
     */
    public static synchronized Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }

        return instance;
    }

    /**
     * 懒汉模式二 
     * 同步代码块
     */
    public static Singleton getInstance() {
        synchronized (Singleton.class) {
            if (instance == null) {
                instance = new Singleton();
            }
        }

        return instance;
    }
}

同步代码,或者同步代码块,效率低

 

双重锁检查

public class Singleton {

    private static volatile Singleton instance = null;

    public static Singleton getInstance() {
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }

        return instance;
    }
}

线程安全,提高效率

 

内部静态类

public class Singleton {

    private static class SingletonHandler {
        private static Singleton instance = new Singleton();
    }

    public static Singleton getInstance() {
        return SingletonHandler.instance;
    }
}

 

常见应用场景

1. 计数器

2. 共享日志

3. Web应用配置对象

4. 数据库连接池

5. 多线程连接池

 

好处

资源共享的情况下,避免由于资源操作时导致的性能或损耗等。如日志文件,应用配置

控制资源的情况下,方便资源之间的互相通信。如线程池

 

posted on 2017-03-31 09:43  alex_cool  阅读(317)  评论(0编辑  收藏  举报