如何使用dagger2设置和获取模型类的Singleton对象? [英] How to set and get Singleton object of a model class using dagger2?

查看:167
本文介绍了如何使用dagger2设置和获取模型类的Singleton对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我已经添加了一个示例模型类中的一个

p>

  public class User 
{
private String email;
private String name;
public String getEmail(){return this.email; }
public void setEmail(String email){this.email = email; }
public String getName(){return this.name; }
public void setName(String name){this.name = name;
}

我想要一旦数据存储在模型类中,它可以在任何活动,类或片段中检索。我应该使用单身吗,还是有更好的方法?



匕首在这种情况下可以工作吗? dagger2是创建单身人士的替代方案吗?



感谢

解决方案

============问题1 - 我有哪些选项? ... ===============



在Android中使用Singletons有许多陷阱。最大的是Android管理您的应用程序的生命周期。因此任何活动都可以随时被销毁。或者Android甚至可能选择杀死你的进程,如果需要其他目的的内存。 Android会恢复您的应用/活动,但是如果您什么也不做,状态就会丢失。在进程杀死场景中,您有一个新的虚拟机实例,并且Singleton对象中的任何状态都将丢失。当然,如果你小心编写代码,你可以确保在正确的状态下重新创建这些代码。这可能很难,容易出错。



如果您需要从应用程序中的任何活动中提供这些模型类,则可以使用几种更好的方法: p>

选项1。



使用意图将对象从活动传递到活动。这解决了全球可用的问题。这也需要您使您的模型类可扩展的或可序列化的。
ii。使用 onSaveInstanceState 方法来保存活动中对象的状态。恢复 onCreate 方法中的状态。
此处描述此过程。



这种方法可能会令人尴尬的是,在每次活动转换时始终写入和读取Intent所需的开销和额外代码。



选项2



考虑让您的单身份人员在每次写入时都会保留其数据,并在每次阅读时从持久性读取。您可以使用多个持久性机制,包括:SharedPreferences,基本文件I / O和SQL数据库。这些选项在此讨论: http://developer.android.com/guide /topics/data/data-storage.html 。如果你去这条路线,我个人觉得SharedPreferences是最容易使用的。



这里是一个例子,说明它可以如何完成

  public class User {

// ------------------ ---
// Singleton实现。注意这只是这种模式的几种风格之一
//。
private static User instance = new User();
private User(){} //防止实例化
public User getUserInstance(){return instance; }
// ---------------------

private String category =user_bean_settings;
private String emailKey =email;
private String nameKey =name;

public String getEmail(){
return readStringProperty(emailKey);
}
public void setEmail(String email){
writeStringProperty(emailKey,email);
}
public String getName(){
return readStringProperty(nameKey);
}
public void setName(String name){
writeStringProperty(nameKey,name);
}

private String readStringProperty(String prop){
Context context = getApplicationContext();
SharedPreferences prefs = context.getSharedPreferences(category,Context.MODE_PRIVATE);
return prefs.getString(prop,null);
}

private void writeStringProperty(String prop,String value){
Context context = getApplicationContext();
SharedPreferences prefs = context.getSharedPreferences(category,Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(prop,value);
editor.commit();
}
}

其中一个尴尬的部分是你需要有一个上下文引用方便地访问SharedPreferences。最好的方法是你的电话。请记住,活动本身是上下文,所以你可以通过。有很多不同的方法来处理这个问题。



=======问题2 - dagger2是创建单身人士的替代方法吗? ==========



我看着匕首2,看到它是一个依赖注入框架。使用DI框架(松散耦合,可测试性...)有很多好处。您可以使用Dagger(或其他DI框架,如RoboGuice)来管理您的单身人士。如果这是您的目标,我个人认为不值得额外的整合努力。然而,如果您想享受上述DI的其他一些益处,那么这可能值得您一些。请记住,这些不免费,您仍然需要遵循良好的编码实践。不过,这似乎已经超出了问题的范围。


What options do I have to make a single instance of all the models classes in an Android application?

I have added below one of the sample model classes

public class User
{
    private String email;
    private String name;
    public String getEmail()           {  return this.email;    }
    public void setEmail(String email) {  this.email = email;   }
    public String getName()            {  return this.name;    }
    public void setName(String name)   {  this.name = name;   }
}

I want that once data is stored in the Model Class, it can be retrieved in any activity, class, or fragment. Should I use a singleton, or is there any better approach available ?

Will dagger2 work in this scenario? Is dagger2 an alternative to creating a singleton?

Thanks

解决方案

============ Question 1 - What options do I have... ===============

There are many pitfalls to using Singletons in Android. The biggest of which is that Android manages the life-cycle of your application. Thus any activity could be destroyed at any time. Or Android may even choose to kill your process if memory is needed for other purposes. Android will restore your app/activity, however if you do nothing, state is lost. In the process-kill scenario, you have a new instance of the VM, and any state in Singleton objects is lost. Of course if you code with care, you can ensure that these are appropriately re-created with the correct state. This can be hard and error-prone.

If you need these model classes available from any activity in your app, there are several somewhat better approaches you can take:

Option 1.

i. Pass the objects from activity to activity using Intents. This solves the "globally available" problem. This will also require you to make your model classes Parcelable or serializable. ii. Use the onSaveInstanceState method to save the state of objects in your activity. Restore the state in the onCreate method. This process is described here.

What might be awkward about this approach is the overhead and extra code required to always write-to and read-from Intent on every activity transition.

Option 2

Consider having your singletons persist their data on every write, and read from persistence on every read. You have multiple persistence mechanisms at your disposal including: SharedPreferences, Basic File I/O, and SQL Database. These options are discussed here: http://developer.android.com/guide/topics/data/data-storage.html. If you go this route, personally I have found SharedPreferences to be the easiest to work with.

Here is an example of how it might be done

public class User {

    //---------------------
    // Singleton implementation.  Note this is just one of several styles
    // of this pattern.
    private static User instance = new User();
    private User() {} // prevent instantiation
    public User getUserInstance() { return instance; }
    //---------------------

    private String category = "user_bean_settings";
    private String emailKey = "email";
    private String nameKey = "name";

    public String getEmail() {
        return readStringProperty(emailKey);
    }
    public void setEmail(String email) {
        writeStringProperty(emailKey, email);
    }
    public String getName() {
        return readStringProperty(nameKey);
    }
    public void setName(String name) {
        writeStringProperty(nameKey, name);
    }

    private String readStringProperty(String prop) {
        Context context = getApplicationContext();
        SharedPreferences prefs = context.getSharedPreferences(category, Context.MODE_PRIVATE);
        return prefs.getString(prop, null);
    }

    private void writeStringProperty(String prop, String value) {
        Context context = getApplicationContext();
        SharedPreferences prefs = context.getSharedPreferences(category, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString(prop, value);
        editor.commit();
    }
}

The one awkward part of this is that you will need to have a Context reference handy to access SharedPreferences. How best to do that is your call. Keep in mind that Activities themselves are Contexts so you can alway pass that. There are lots of different ways to handle this.

======= Question 2 - Is dagger2 an alternative to creating a singleton?... ==========

I looked at Dagger 2 and see that it is a dependency injection framework. There are many benefits to using a DI framework (loose coupling, testability, ...). You could use Dagger (or another DI framework like RoboGuice) to manage your singletons. If that is your only objective, I personally would not think it is worth the additional effort of integration. If however you want to enjoy some of the other benefits of DI mentioned above, then it might be worth your while. Keep in mind that these do not come for free, you still need to follow good coding practices. Anways, this seems to have gone a bit beyond the scope of the question.

这篇关于如何使用dagger2设置和获取模型类的Singleton对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆