Objective-C:何时知道你在滥用全局变量的SIngleton方法 [英] Objective-C: When to know that you are abusing the SIngleton method of Global Variables
问题描述
我的问题是,如何维护一个具有不相关全局变量的大型单例对象,以及通常是最佳实践非平凡的iphone应用程序?
非常感谢您的建议!
在解耦设计的上下文中对此问题进行了详细分析 。我会尽量总结我的观点:
- 如果您的Singleton具有显着的全局状态,请不要使用Singleton。这包括持久性存储,如数据库,文件等。
- 在类名不依赖单例对象的情况下,应该注入依赖关系。将Singleton实例注入类的需求证明了该模式的错误用法(请参见第1点)。
- 假设Singleton的生命周期与应用程序的生命周期相同。大多数Singleton实现都使用延迟加载机制来实例化自己。这是微不足道的,它们的生命周期不太可能改变,否则你不应该使用Singleton。
So my clients iphone app has balloned from 5 or so classes to over 25 in the last few weeks. With such a large (for the iphone anyway) class structure I've been utilizing the Singleton class for accessing global variables. The problem is that whenever I need to access a variable outside of the class I'm working on, I have a choice of either modifying the code to pass a reference to the variable or just throw it in the singleton. Of course throwing it in the singleton is a lot less code and effort, however, now the singleton is beginning to look like a mish-mosh of unrelated globals.
My question is how appropriate is it to maintain a large singleton object with unrelated global vars and what is generally the "best practice" way of sharing data across classes in a "non-trivial" iphone app?
Many thanks in advance for your advice!
I have done a detailed analysis of this problem in the context of a decoupled design. I'll try to summarize my points:
- If your Singleton carries a significant global state, don’t use Singleton. This includes persistent storage such as Databases, Files etc.
- In cases, where dependency on a Singleton Object is not obvious by the classes name, the dependency should be injected. The need to inject Singleton Instances into classes proves a wrong usage of the pattern (see point 1).
- A Singleton’s life-cycle is assumed to be the same as the application’s. Most Singleton implementations are using a lazy-load mechanism to instantiate themselves. This is trivial and their life-cycle is unlikely to change, or else you shouldn’t use Singleton.
这篇关于Objective-C:何时知道你在滥用全局变量的SIngleton方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!