Objective-C:何时知道你在滥用全局变量的SIngleton方法 [英] Objective-C: When to know that you are abusing the SIngleton method of Global Variables

查看:203
本文介绍了Objective-C:何时知道你在滥用全局变量的SIngleton方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我的客户iPhone应用程序在过去的几周里已经从5个左右的班级放到了25个以上。有了这么大的(对于iPhone来说)类结构,我一直在使用Singleton类来访问全局变量。问题是,无论何时我需要访问我正在处理的类之外的变量,我都可以选择修改代码以将引用传递给变量,或者将其引入单例中。当然,将它扔到单身人士中的代码和努力要少很多,但是现在单身人士似乎开始看起来像不相干的全局变量。



我的问题是,如何维护一个具有不相关全局变量的大型单例对象,以及通常是最佳实践非平凡的iphone应用程序?



非常感谢您的建议!

解决方案

在解耦设计的上下文中对此问题进行了详细分析 。我会尽量总结我的观点:


  1. 如果您的Singleton具有显着的全局状态,请不要使用Singleton。这包括持久性存储,如数据库,文件等。

  2. 在类名不依赖单例对象的情况下,应该注入依赖关系。将Singleton实例注入类的需求证明了该模式的错误用法(请参见第1点)。

  3. 假设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:

  1. If your Singleton carries a significant global state, don’t use Singleton. This includes persistent storage such as Databases, Files etc.
  2. 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).
  3. 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屋!

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