单例模式
单例模式
Android:常用的设计模式
Builder模式:比如AlertDialog.Builder。
适配器模式:比如GridView、ListView与Adapter。
命令模式:比如Handler.post。
享元模式:比如Message.obtain。
单例模式:比如InputMethodManager.getInstance。
观察者模式:比如ContentObserver。
这是一些经常用到的设计模式以及举例
单例模式(Singleton):保证一个类仅有一个实例,并提供一个访问它的全局访问点
优点; 延迟加载,需要加载的时候才会去加载;
缺点:会出现线程不安全的问题,在多线程的时候会出现不同步的情况
优点
系统内存中该类只存在一个对象,节省了系统资源,对于一些需要频繁创建销毁的对象,使用单例模式可以提高系统性能。
缺点
当想实例化一个单例类的时候,必须要记住使用相应的获取对象的方法,而不是使用new,可能会给其他开发人员造成困扰,特别是看不到源码的时候。
1.常驻内存
2.构造方法私有化
3.static 里面的getInstance();
适用场合
- 需要频繁的进行创建和销毁的对象;
- 创建对象时耗时过多或耗费资源过多,但又经常用到的对象;
- 工具类对象;
- 频繁访问数据库或文件的对象。
getInstance;
①:在get时判空 instance!=null ,单例模式容易失效;
加个锁(stock...),但是会让进程变慢;
②:加一个锁
③:加两个锁
④::成员变量在实例化的时候就会new出来
private static 类 instance = new 类 ; 会消耗内存
单例模式的八种模式
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 Singleton singleton; private Singleton() {} public static Singleton getInstance() { if (singleton == null) { singleton = new Singleton(); } return singleton; } }
4.懒汉式(线程安全,同步方法)[不推荐用]
public class Singleton { private static Singleton singleton; private Singleton() {} public static synchronized Singleton getInstance() { if (singleton == null) { singleton = new Singleton(); } return singleton; } }
缺点:效率太低了,每个线程在想要获得类的实例的时候,执行getInstance()就可以同步,这个方法只执行一次就够了,后面要想得到该实例,直接return就好,所以同步效率太低了;
5.懒汉式(线程安全,同步代码块)[不可用]
public class Singleton { private static Singleton singleton; private Singleton() {} public static Singleton getInstance() { if (singleton == null) { synchronized (Singleton.class) { singleton = new Singleton(); } } return singleton; } }
缺点就是不能起到线程同步的作用;
6.双重检查[推荐用]
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; } }
7.静态内部类[推荐用]
public class Singleton { private Singleton() {} private static class SingletonInstance { private static final Singleton INSTANCE = new Singleton(); } public static Singleton getInstance() { return SingletonInstance.INSTANCE; } }
优点:避免了线程不安全,延迟加载,效率高。
8.枚举
public enum Singleton { INSTANCE; public void whateverMethod() { } }