mmp写的一遍不知道怎么回事 发表之后只有一半 不写了 直接上代码
public class ExampleApp extends Application { @Override public void onCreate() { super.onCreate(); Latte.init(this) .withApiHost("http://127.0.0.1/") .configure(); } }
public final class Latte { public static Configurator init(Context context){ getConfigurations().put(ConfigType.APPLICATION_CONTEXT.name(),context.getApplicationContext()); return Configurator.getInstance(); } public static WeakHashMap<String,Object> getConfigurations(){ return Configurator.getInstance().getLatteConfigs(); } }
public class Configurator { private static final WeakHashMap<String ,Object> LATTE_CONFIGS = new WeakHashMap<>(); private Configurator(){ LATTE_CONFIGS.put(ConfigType.CONFIG_READY.name(),false); } public static Configurator getInstance(){ return Holder.INSTANCE; } private static class Holder{ private static final Configurator INSTANCE = new Configurator(); } final WeakHashMap<String ,Object> getLatteConfigs(){ return LATTE_CONFIGS; } public final void configure(){ LATTE_CONFIGS.put(ConfigType.CONFIG_READY.name(),true); } public final Configurator withApiHost(String host){ LATTE_CONFIGS.put(ConfigType.API_HOST.name(),host); return this; } private void checkConfiguration(){ final boolean isReady = (boolean) LATTE_CONFIGS.get(ConfigType.CONFIG_READY.name()); if (!isReady){ throw new RuntimeException("Configuration is not ready,call configure"); } } final <T> T getConfiguration(Enum<ConfigType> key){ checkConfiguration(); return (T) LATTE_CONFIGS.get(key.name()); } }
public enum ConfigType { API_HOST, APPLICATION_CONTEXT, CONFIG_READY, ICON }