android – Dagger 2 Singleton vs Real Singleton

I want to use daggers in my project. 2. Dagger provides a good method to create singletons. I have some in the project, but dagger creates a new object graph and each new container for each @ singleton object, so we must create components at the application level. We should provide singleton classes for applications, which doesn't look good: (. The question is: should I keep my old bachelor? Or should I use a dagger?

resolvent:

Dagger is a better way to manage singles, in part because you don't have to worry about how to replace these singles in unit tests: your singles will be injected (i.e. constructor parameters) and accessible fields) in ways you can control and override in unit tests

If you need an application level singleton, you need to keep the same component instance in the life cycle of the application instead of creating a new component instance for each new "container". The component will contain and provide singletons, so you don't need to activate multiple object graphs in the application. If an external creator (such as Android or servlet engine) Create your own objects outside of dagger, which may mean that you need to save the dagger component in the singleton holder (which may be a thread safe public static field) for your old singles; This should still be easier to understand and maintain, because you can provide as many singletons as possible through dagger, and only worry about an external management singleton of the component itself

As an alternative, you can keep the old singletons exactly as they are, and write the @ provides method in the module to retrieve the singleton instances when the objects created by dagger request them. In this way, you can create a new object graph anytime, anywhere, and your singles will still appear as singles. However, I will warn you about this, because at this point, Your singles can access your application in two different ways. Only those created or managed by dagger will be easily covered in the test; This can be confusing and difficult to manage

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>