c# 单例模式

1.一种软件设计模式;

2.定义:单例对象的类只允许一个实例存在;

3.应用背景:

  许多时候只需要拥有一个的全局对象,这样有利于协调整体的行为。

  比如在某个服务器中,该服务器的配置信息存放在一个文件中,这些配置数据由一个单例对象统一获取。

4.组成部分:

  1.构造方法为私有,这样保证唯有通过该类提供的静态方法获得该类的唯一实例。

  2.获得该实例的方法(通常使用getInstance这个名字),为静态。

5.注意事项:

  1.多线程避免两个线程同时调用,那么它们同时没有检测到唯一实例的存在,从而同时各自创建一个。这样违背单例模式的唯一原则。

6.写法例子:

  1.饿汉式(静态常量):

public class Singleton {

    private final static Singleton INSTANCE = new Singleton();

    private Singleton(){}

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

  2.饿汉式(静态代码块):

public class Singleton {

    private static Singleton instance;

    static {
        instance = new Singleton();
    }

    private Singleton() {}

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

   3.双重检查:

public class Singleton {

    private static volatile Singleton singleton;

    private Singleton() {}

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

   4.静态内部类:

public class Singleton {

    private Singleton() {}

    private static class SingletonInstance {
        private static final Singleton INSTANCE = new Singleton();
    }

    public static Singleton getInstance() {
        return SingletonInstance.INSTANCE;
    }
}

 7.适用场合:

  1.需频繁的进行创建和销毁的对象;

  2.创建对象时耗时过多或浪费资源过多;

  3.工具类对象;

  4.频繁访问数据库或文件的对象;

posted @ 2018-11-14 10:16  风影我爱罗  阅读(171)  评论(0编辑  收藏  举报