设计模式1——单例模式

 

一、单例模式的定义

Ensure  a  class has only one instance , and  provide  a global point of access to it.(确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例)

二 、单例模式的应用

       1 、单例模式的优点

            1)由于单例模式在内存中只有一个实例,减少了内存开支,特别是一个对象需要频繁的创建,销毁时,而且创建或销毁时的性能又无法优化,单例模式的优势就非常明显

            2)由于单例模式只生成一个实例,所以减少了系统的性能开销,当一个对象的产生需要比较多的资源时,如读取配置,产生其他依赖对象时,可以通过在应用启动时直接产生一个单例对象,然后用永久驻留内存的方式来解决。

            3)单例模式可以避免对资源的多重占用,例如一个写文件动作,由于只有一个实例存在内存中,避免对同一个文件的同时写操作。

       2、单例模式的缺点

            1)单例模式一般没有接口,扩展很困难,若要扩展,除了修改代码基本上没有第二张途径可以实现,单例模式为什么不能增加接口呢?因为接口对单例模式是没有任何意义的,他要求"自行实例化",并且提供单一实例,接口抽象类是不可能被实例化的,当然在特俗情况下,单例模式可以实现接口,被继承,需要在系统开发中根据环境判断。

            2)单例模式对测试是不利的,在并行开发环境中,如果单例模式没有完成,是不能进行测试的,没有接口也不能使用mock的方式虚拟一个对象。

            3)单例模式与单一职责原则有冲突,一个类应该只实现一个逻辑,而不关心他是否单例的,是不是要单例取决于环境,单例模式把"要单例"和业务逻辑融合在一个类中。

       3、单例模式的使用场景

           在一个系统中,要求一个类有且只有一个对象,如果出现多个就会出现不良反应,可以采用单例模式,具体的场景如下。

            1)要求生成唯一序列号的环境。

            2)在整个项目中,需要一个共享访问点或共享数据,例如一个web页面上的计数器,可以不用把每次刷新都记录刀数据库中,使用单例模式保持计数器的值,并确保是线程安全的。

            3)创建一个对象需要消耗的资源过多,如要访问IO和数据库等资源,

            4)需要定义大量的静态常量和静态方法(如工具类)的环境,可以采用单例模式。

       4、单例模式的注意事项

        在高并发的情况下请除以线程同步问题,可以有几种的实现方式。

三   单例模式的写法

public class Singleton {

    /**
     *饿汉式静态常量
     * 这种写法比较简单,就是在类装载的时候就完成实例化。避免了线程同步问题。
     * 在类装载的时候就完成实例化,没有达到Lazy Loading的效果。如果从始至终从未使用过这个实例,则会造成内存的浪费。
     */
    public  static class Singleton1 {

        private final static Singleton1 INSTANCE = new Singleton1();

        private Singleton1(){

        }
        public static Singleton1 getInstance(){

            return INSTANCE;
        }


    }

    /**
     *饿汉式(静态代码块)
     *这种方式和上面的方式其实类似,只不过将类实例化的过程放在了静态代码块中,
     * 也是在类装载的时候,就执行静态代码块中的代码,初始化类的实例。优缺点和上面是一样的。
     */
    public static class Singleton2 {
        private final  Singleton2 instance ;
        {
            instance  = new Singleton2();
        }
        private Singleton2() {}

        public Singleton2 getInstance() {
            return instance;
        }



    }

    /**
     * 懒汉式(线程不安全)
     *这种写法起到了Lazy Loading的效果,但是只能在单线程下使用。如果在多线程下,
     * 一个线程进入了if (singleton == null)判断语句块,还未来得及往下执行,另一个线程也通过了这个判断语句,
     * 这时便会产生多个实例。所以在多线程环境下不可使用这种方式。
     */
    public static class Singleton3 {
        private static Singleton3 singleton;
        private Singleton3() {}

        public static Singleton3 getInstance() {
            if (singleton == null) {
                singleton = new Singleton3();
            }
            return singleton;
        }


    }

    /**
     *懒汉式(线程安全,同步方法)
     * 解决上面第三种实现方式的线程不安全问题,做个线程同步就可以了,于是就对getInstance()方法进行了线程同步。
     * 缺点:效率太低了,每个线程在想获得类的实例时候,执行getInstance()方法都要进行同步。
     * 而其实这个方法只执行一次实例化代码就够了,后面的想获得该类实例,直接return就行了。方法进行同步效率太低要改进
     */
    public static class Singleton4 {
        private static Singleton4 singleton;

        private Singleton4() {}

        public static synchronized Singleton4 getInstance() {
            if (singleton == null) {
                singleton = new Singleton4();
            }
            return singleton;
        }

    }

    /**
     * 懒汉式(线程安全,同步代码块) 线程不安全
     *由于第四种实现方式同步效率太低,所以摒弃同步方法,
     * 改为同步产生实例化的的代码块。但是这种同步并不能起到线程同步的作用。跟第3种实现方式遇到的情形一致,
     * 假如一个线程进入了if (singleton == null)判断语句块,还未来得及往下执行,另一个线程也通过了这个判断语句,
     * 这时便会产生多个实例。
     */
    public static class Singleton5 {
        private static Singleton5 singleton;

        private Singleton5() {}

        public static  Singleton5 getInstance() {

            if (singleton == null) {
                synchronized (Singleton5.class){
                    singleton = new Singleton5();
                }
            }
            return singleton;
        }

    }

    /**
     * 懒汉式双重检查
     * Double-Check概念对于多线程开发者来说不会陌生,如代码中所示,我们进行了两次if (singleton == null)检查,
     * 这样就可以保证线程安全了。这样,实例化代码只用执行一次,
     * 后面再次访问时,判断if (singleton == null),直接return实例化对象
     */
    public  static class Singleton6 {
        private static volatile Singleton6 singleton;

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

    }

    /**
     * 静态内部类
     *这种方式跟饿汉式方式采用的机制类似,但又有不同。两者都是采用了类装载的机制来保证初始化实例时只有一个线程。
     * 不同的地方在饿汉式方式是只要Singleton类被装载就会实例化,没有Lazy-Loading的作用,
     * 而静态内部类方式在Singleton类被装载时并不会立即实例化,而是在需要实例化时,调用getInstance方法,
     * 才会装载SingletonInstance类,从而完成Singleton的实例化。类的静态属性只会在第一次加载类的时候初始化,
     * 所以在这里,JVM帮助我们保证了线程的安全性,在类进行初始化时,别的线程是无法进入的。
     * 优点:避免了线程不安全,延迟加载,效率高。
     */

    public static class Singleton7 {
        private Singleton7() {}

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

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


    }

    /**
     * 枚举
     *
     * 借助JDK1.5中添加的枚举来实现单例模式。不仅能避免多线程同步问题,
     * 而且还能防止反序列化重新创建新的对象。可能是因为枚举在JDK1.5中才添加,
     * 所以在实际项目开发中,很少见人这么写过。
     */
    public  enum  Singleton8 {

        Instance;

        public void anyMethod(){}


    }

  /**
     * 使用容器实现单例
     * 在程序的初始,将多种单例注入到体格同意的管理类中,在使用时根据key获取对象对应类型的对象
     * 优点  可以管理多种类型的单例,并且在使用时可以通过统一的接口进行获取操作,
     * 降低了用户的使用成本,也对用户隐藏了具体实现,降低了耦合度
     */
    public static class Singleton9 {

        private static Map<String, Object> map = new HashMap();

        private Singleton9() {
        }


        public static void getInstance(String key, Singleton9 singleton) {

            if (!map.containsKey(key)) {
                map.put(key, singleton);
            }
        }

        public static Object getInstance(String key) {

            return map.get(key);
        }

    }
}

四 单例模式在Android源码中的使用(不同Android版本会有差异)

    android系统中,我们经常会通过Context获取系统级别的服务,如WindowsManagerService、ActivityManagerService等,更常用的一个是LayoutInFlater类

 

 /**
  * Obtains the LayoutInflater from the given context.
  */
 public static LayoutInflater from(Context context) {
     LayoutInflater LayoutInflater =
                (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        if (LayoutInflater == null) {
            throw new AssertionError("LayoutInflater not found.");
        }
        return LayoutInflater;
 }

 

往下追踪可以在Context 实现类ContextImp中看到 

  @Override
    public Object getSystemService(String name) {
        return SystemServiceRegistry.getSystemService(this, name);
    }

 

在SystemServiceRegistry中可以看到

 /**
     * Gets a system service from a given context.
     */
    public static Object getSystemService(ContextImpl ctx, String name) {
        ServiceFetcher<?> fetcher = SYSTEM_SERVICE_FETCHERS.get(name);
        return fetcher != null ? fetcher.getService(ctx) : null;
    }

也就是上文中第九种实现方式

InputMethodManager类  

public final class InputMethodManager {
    static final boolean DEBUG = false;
    static final String TAG = "InputMethodManager";

    static InputMethodManager mInstance;
    
   
  /**
     * Retrieve the global InputMethodManager instance, creating it if it
     * doesn't already exist.
     * @hide
     */
    static public InputMethodManager getInstance(Context context) {
        return getInstance(context.getMainLooper());
    }
    
    /**
     * Internally, the input method manager can't be context-dependent, so
     * we have this here for the places that need it.
     * @hide
     */
    /**
     * Retrieve the global InputMethodManager instance, creating it if it
     * doesn't already exist.
     * @hide
     */
    public static InputMethodManager getInstance() {
        synchronized (InputMethodManager.class) {
            if (sInstance == null) {
                try {
                    sInstance = new InputMethodManager(Looper.getMainLooper());
                } catch (ServiceNotFoundException e) {
                    throw new IllegalStateException(e);
                }
            }
            return sInstance;
        }
    }

 

 

AccessibilityManager类

 

public final class AccessibilityManager {
    private static AccessibilityManager sInstance = new AccessibilityManager(null, null, 0);

 
 /**
     * Get an AccessibilityManager instance (create one if necessary).
     *
     */
    public static AccessibilityManager getInstance(Context context) {
        return sInstance;
    }

}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值