单例模式
意图:这种模式涉及到一个单一的类,该类负责创建自己的对象,同时确保只有单个对象被创建。这个类提供了一种访问其唯一的对象的方式,可以直接访问,不需要实例化该类的对象。
public class Singleton { private static Singleton instance = new Singleton(); private Singleton (){} public static Singleton getInstance() { return instance; } } 1. 私有静态的对象实例 2. 私有构造方法 3. 静态获取方法public class RetrofitManager { private static HashMap<String,List<Cookie>> hashMap = new HashMap<>(); private static OkHttpClient httpClient = new OkHttpClient.Builder().cookieJar(new CookieJar() { @Override public void saveFromResponse(@NonNull HttpUrl httpUrl, @NonNull List<Cookie> list) { hashMap.put(httpUrl.host(), list); } @NonNull @Override public List<Cookie> loadForRequest(@NonNull HttpUrl httpUrl) { List<Cookie> cookies = hashMap.get(httpUrl.host()); return cookies == null ? new ArrayList<>() : cookies; } }).build(); private static Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://r87bkar939.execute-api.us-west-2.amazonaws.com/") .callFactory((Call.Factory) httpClient) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava3CallAdapterFactory.create()) .build(); private RetrofitManager (){ } public static Retrofit getInstance(){ return retrofit; } }
注意:当生成对象需要其他对象时候,其他对象必须也是类的。
类方法里不能实例非静态对象
标签:Singleton,对象,模式,static,private,单例,new,Android,public From: https://www.cnblogs.com/remix777/p/17586795.html