这是一个例子,但是!虽然这可能是闪亮的,易于使用,但单身人士是邪恶的.尽可能避免使用它们.解决它的一种方法是使用依赖注入.
无论如何.
public class Api {
private static Api instance = null;
public static final String BASE_URL = "your_base_url";
// Keep your services here, build them in buildRetrofit method later
private UserService userService;
public static Api getInstance() {
if (instance == null) {
instance = new Api();
}
return instance;
}
// Build retrofit once when creating a single instance
private Api() {
// Implement a method to build your retrofit
buildRetrofit(BASE_URL);
}
private void buildRetrofit() {
Retrofit retrofit = ...
// Build your services once
this.userService = retrofit.create(UserService.class);
...
}
public UserService getUserService() {
return this.userService;
}
...
}
Run Code Online (Sandbox Code Playgroud)
现在你把所有东西放在一个地方.用它.
UserService userService = Api.getInstance().getUserService();
Run Code Online (Sandbox Code Playgroud)
要实现单例类,最简单的方法是将类的构造函数设置为私有。
在急切初始化中,单例类的实例在类加载时创建,这是创建单例类最简单的方法。
public class SingletonClass {
private static volatile SingletonClass sSoleInstance = new SingletonClass();
//private constructor.
private SingletonClass(){}
public static SingletonClass getInstance() {
return sSoleInstance;
}
}
Run Code Online (Sandbox Code Playgroud)
该方法将检查是否已经创建了该类的任何实例?如果是,那么我们的方法 (getInstance()) 将返回旧实例,如果不是,那么它将在 JVM 中创建单例类的新实例并返回该实例。这种方法称为延迟初始化。
public class SingletonClass {
private static SingletonClass sSoleInstance;
private SingletonClass(){} //private constructor.
public static SingletonClass getInstance(){
if (sSoleInstance == null){ //if there is no instance available... create new one
sSoleInstance = new SingletonClass();
}
return sSoleInstance;
}
}
Run Code Online (Sandbox Code Playgroud)
还有一些东西,比如Java Reflection API、Thread Safe 和 Serialization safe Singleton。
请查看此参考以获取更多详细信息并深入了解单例对象创建。
https://medium.com/@kevalpatel2106/digesting-singleton-design-pattern-in-java-5d434f4f322#.6gzisae2u
| 归档时间: |
|
| 查看次数: |
7399 次 |
| 最近记录: |