《Android源码设计模式解析和实战》单例设计模式

单例设计模式是最简单也是最常用的设计模式;介绍单例模式几种使用;
1:饿汉式 静态 第一次加载直接初始化


public class Person_1 {
private static Person_1 person = new Person_1();
private Person_1() {
}
public static Person_1 getInstance() {
return person;
}
}

2:懒汉式 使用时初始化(getInstance())

  1. 每次都需要同步


    public class Person_3 {
    private static Person_3 person_3;
    private Person_3() {
    }
    public static synchronized Person_3 getInstance() {
    if (person_3 == null) {
    person_3 = new Person_3();
    }
    return person_3;
    }
    }

    2)Double Check Lock(DCL) 实现单例
    双重判断避免不必要的同步;

    public class Person_2 {
    private static Person_2 person_2;
    private Person_2() {
    }
    public static Person_2 getInstance() {
    if (person_2 == null) {
    synchronized (Person_2.class) {
    if (person_2 == null) {
    person_2 = new Person_2();
    }
    }
    }
    return person_2;
    }
    }

  2. 静态内部类单例模式
    第一次调用getInstance() 才会初始化


    public class Person_4 {
    private Person_4() {
    }
    private static Person_4 person_4;
    public static Person_4 getInstance() {
    return SingleHolder.person_4;
    }
    private static class SingleHolder {
    private static final Person_4 person_4 = new Person_4();
    }
    }

    4)枚举

    public enum Person_5 {
    INSTANCE;
    @Override
    public String toString() {
    return super.toString();
    }
    }

    5)使用容器

    public class SingletonUtils {
    private static HashMap singletonMap = new HashMap<>();

    private SingletonUtils() {

    }

    public static void setSingleton(String key, Object value) {
    if (!singletonMap.containsKey(key)) {
    singletonMap.put(key, value);
    }
    }

    public static Object getSingleton(String key) {
    return singletonMap.get(key);
    }
    }

你可能感兴趣的:(《Android源码设计模式解析和实战》单例设计模式)