单例模式很适合Android开发,对于Retrofit(Android开发中一个非常优秀的Rest Client),也要使用单例模式获取实例。
下面是Jake大神在stackoverflow上关于Retrofit的使用问题的回答。
Both the RestAdapter and the generated instance of your services (MyTaskService in this case) are extremely expensive objects and should be used as singletons.
This means that you should only ever call restAdapter.create once and re-use the same instance of MyTaskService every time you need to interact with.
I cannot stress this enough.
You can use the regular singleton pattern in order to ensure that there only is ever a single instance of these objects that you use everywhere. A dependency injection framework would also be something that could be used to manage these instances but would be a bit overkill if you are not already utilizing it.
从中我们可以看到 Jake表示 Retrofit每次创建RestAdapter和自定义的接口对象是很耗费资源的,因此不需要每次去创建,要使用单例模式。确实Retrofit是通过添加运行时注解,采用动态代理的方式去创建实例的。
查看更多