如果存在多个改造调用,如何使改造单例,这样类中就不会有重复的代码,从而去掉不必要的代码。
发布于 2017-01-16 17:22:58
这里有一个例子,但是!虽然这可能是闪亮和易于使用的,但单例是邪恶的。如果可能的话,尽量避免使用它们。一种解决方法是使用依赖注入。
不管怎么说。
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;
}
...
}现在你已经把所有东西都放在一个地方了。使用它。
UserService userService = Api.getInstance().getUserService();发布于 2017-01-16 17:00:44
要实现单例类,最简单的方法是将类的构造函数设为私有。
在急切初始化中,单例类的实例是在类加载时创建的,这是创建单例类的最简单的方法。
public class SingletonClass {
private static volatile SingletonClass sSoleInstance = new SingletonClass();
//private constructor.
private SingletonClass(){}
public static SingletonClass getInstance() {
return sSoleInstance;
}
}懒惰的initialization:
此方法将检查是否已经创建了该类的任何实例?如果是,那么我们的方法(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;
}
}还有更多的东西,像Java反射API,线程安全和序列化安全单例。
有关单例对象创建的更多详细信息和深入理解,请查看此参考。
https://medium.com/@kevalpatel2106/digesting-singleton-design-pattern-in-java-5d434f4f322#.6gzisae2u
发布于 2017-01-17 11:09:35
public class Singleton {
private volatile static Singleton singleton;
private Singleton(){}
public static Singleton getSingleton(){
if (singleton == null) {
synchronized (Singleton.class) {
if (singleton == null) {
singleton = new Singleton();
}
}
}
return singleton;
}https://stackoverflow.com/questions/41672427
复制相似问题