单例类与具有静态成员的类 [英] Singleton class vs. class with static member

查看:49
本文介绍了单例类与具有静态成员的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尽管有关该主题的话题很多,但我仍然不清楚何时选择哪种方法.我希望通过讨论一个具体的例子,我最终会明白".

Despite the many threads on that topic, I am still unclear as to when to choose which approach. I am hoping that by discussing a specific example, I will finally "get it."

注意:我在这里的语言是 Cocoa,尽管一般问题不是特定于语言的.

Note: My language here is Cocoa though the general issue is not language-specific.

我有一个类 TaskQueue 想用来:

I have a class TaskQueue that I want to use to:

  • 从我的代码中的任何位置访问以添加或删除计划任务
  • 定期自动处理计划任务

首次使用 TaskQueue 时,我希望 TaskQueue 启动一个线程,然后该线程会定期唤醒以处理任务.

When TaskQueue is first used, I want TaskQueue to initiate a thread that will then wake up at regular intervals to process the tasks.

显然,我至少需要两个变量:

Obviously, I will need at a minimum two variables:

  • 存储任务的数组
  • 处理任务的线程实例

由于我只想要一个任务队列和一个线程来处理这些任务,所以我有两个选择:

Since I only want one queue of tasks and one thread to process these tasks, I have two choices:

  1. 使 TaskQueue 成为单例类(例如使用 CWL_DECLARE_SINGLETON_FOR_CLASS_WITH_ACCESSOR,如 http://www.cocoawithlove.com/2008/11/singletons-appdelegates-and-top-level.html,我相信我将不得不修改 CWLSynthesizeSingleton.h 文件在初始化时启动线程.)

  1. Make TaskQueue a singleton class (using for example CWL_DECLARE_SINGLETON_FOR_CLASS_WITH_ACCESSOR as described in http://www.cocoawithlove.com/2008/11/singletons-appdelegates-and-top-level.html, which I believe I will have to modify the CWLSynthesizeSingleton.h file to start the thread at init time.)

使任务数组和线程实例都是静态的(遵循此处建议的方法:如何在 Objective-C 中声明类级属性?)

Have the array of tasks and the thread instance both be static (following the approach suggested here: How do I declare class-level properties in Objective-C?)

在这种特定情况下,是否有一种方法明显优于另一种方法?如果是,为什么?

Is there clearly one approach that's better than the other one in this specific case? If so, why?

推荐答案

主要区别很简单,例如:

The main differences are simple things like:

  • 使用单例,您可以为委托和回调传递对象
  • 使用单例,您可以实现接口并派生它
  • 通过单例,您可以使用工厂模式来构建您的实例

如果您不需要它们中的任何一个,就像必须在代码周围访问全局功能一样,那么您可以使用静态方法.

If you don't need any of them, as with global functionality that must be accessed all around your code then you can go with static methods.

我个人更喜欢使用静态方法,除非我有明确的理由使用单例实例(例如具有通用接口但实现不同).

I personally prefer using static methods unless I have an explicit reason to use a singleton instance (such as having a common interface but different implementations).

请注意,将静态方法重构为单例实例是一个非常简单的过程,因此如果您发现需要后者,您将轻松重构它(然后您就有了 C 预处理器,一个 #define 差不多就够了).

Mind the fact that refactoring static methods to a singleton instance is quite a straightforward process so if you ever find the need for the latter you will refactor it easily (then you have the C preprocessor, a single #define would be almost enough).

这篇关于单例类与具有静态成员的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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