单例模式

饿汉模式:

public class Singleton {
   private static final Singleton instance = new Singleton();

   private Singleton() {
   }

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

懒汉模式:

public class Singleton {
    private static Singleton instance;

    private Singleton() {
    }

    public static Singleton getInstance() {
        if (instance == null) {
            instance == new Singleton();
        }
        return instance;
    }
}

Double CheckLock(DCL)实现单例

public class Singleton {
    private static Singleton instance;

    private Singleton() {
    }

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

静态内部类实现单例

public class Singleton {
    private Singleton() {
    }

    public static Singleton getInstance() {
        return SingletonHolder.mInstance;
    }

    /**
     * 静态内部类
     */
    private static class SingletonHolder {
        private static final Singleton mInstance = new Singleton();
    }
}

枚举单例

public class Test {
    public static void main(String args[]) {
        Singleton.INSTANCE.doSomething();
        Singleton.INSTANCE2.doSomething();
    }

    public enum Singleton {
        INSTANCE(1),
        INSTANCE2(2){
            @Override
            public void doSomething() {
                System.out.print("Instance 2");
            }
        };

        public void doSomething() {
            System.out.println("just do it");
        }
        Singleton(int i){
            System.out.println("instance "+i);
        }
    }
}
result:
instance 1
instance 2
just do it
Instance 2

使用容器实现单例模式

public class SingletonManager {
    private static Map objectMap=new HashMap<>();
    
    public static void registerService(String key,Object value){
        if(!objectMap.containsKey(key))
            objectMap.put(key,value);
    }
    public static Object getService(String key){
        return objectMap.get(key);
    }
}

Android源码中的单例模式:

获取服务的时候
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;
    }

你可能感兴趣的:(单例模式)