静态类相对于使用单例的优势 [英] Advantage of Static class over use of Singleton

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

问题描述

单身有什么问题?
单身人士:好的设计还是拐杖?
Singleton:应该如何使用
单身人士有什么不好的地方

<小时>

您可以找到在静态类上使用单例的众多原因.但是肯定在某些情况下最好在单例之前使用静态类.它们是什么?


You can find numerous reasons for using a Singleton over a Static class. But there must surely be some situations where it is better to use a static class before a Singleton. What are they?

推荐答案

您可以在以下情况下使用静态类:

You can use static class when:

1) 它的所有方法都是实用程序(很好的例子 - 类 Math)

1) all its methods are utilities (nice example - class Math)

2) 您不想处理从垃圾收集器(在小程序中)保留您的实例的问题,但我最好在那里使用单例

2) you don't want to deal with preserving your instance from garbage collector (in applets), but I would better use singleton there

3) 你绝对确定它在未来不会变成有状态的,并且你确定你永远只需要那个类的一个实例

3) you are absolutely sure that it wouldn't become stateful in the future and you are sure that you will always need only one instance of that class

如果您正在使用单例并且在某一时刻意识到您需要多个实例,那么您的单例可以很容易地转换为多音,但是您会遇到静态类的问题

If you are using singleton and in one moment you realize that you need several instances then your singleton easily can be transformed to multitone, but you'll have a problem with static class

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

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