问题描述
在决定使用 singleton "> singleton 之间.这样做,您有点被迫对比两者,因此,您可以提出的任何对比都对展示您的思考过程也很有用!另外,每个面试官都喜欢看到说明性的例子. :)
推荐答案
- 单例可以实现接口并从其他类中继承.
- 单身人士可以懒惰.仅当实际需要时.如果初始化包括昂贵的资源加载或数据库连接,那将非常方便.
- 单例提供了一个实际的对象.
- 单身人士可以扩展到工厂.幕后的对象管理是抽象的,因此可以更好地维护并产生更好的代码.
其他推荐答案
"避免两者都"怎么样?单例和静态课程:
- 可以引入全球状态
- 紧密耦合到其他多个类
- 隐藏依赖项
- 可以使单位测试类别孤立地进行困难
相反,请查看依赖项注入和对控制容器的反转库. IOC的几个库将为您处理终生管理.
(与往常一样,有例外,例如静态数学类和C#扩展方法.)
其他推荐答案
我认为唯一的区别是语法:mysingleton.current.whatewate()vs mysingleton.whatever().正如戴维(David)所提到的那样,国家最终都是"静态"的.
编辑:埋葬旅从迪格(Digg)出来...无论如何,我想到了一个需要单身人士的案件.静态类不能从基类继承也不能实现接口(至少在.NET中它们不能).因此,如果您需要此功能,则必须使用单例.
问题描述
Name the design considerations in deciding between use of a singleton versus a static class. In doing this, you're kind of forced to contrast the two, so whatever contrasts you can come up with are also useful in showing your thought process! Also, every interviewer likes to see illustrative examples. :)
推荐答案
- Singletons can implement interfaces and inherit from other classes.
- Singletons can be lazy loaded. Only when it is actually needed. That's very handy if the initialisation includes expensive resource loading or database connections.
- Singletons offer an actual object.
- Singletons can be extended into a factory. The object management behind the scenes is abstract so it's better maintainable and results in better code.
其他推荐答案
How about "avoid both"? Singletons and static classes:
- May introduce global state
- Get tightly coupled to multiple other classes
- Hide dependencies
- Can make unit testing classes in isolation difficult
Instead, look into Dependency Injection and Inversion of Control Container libraries. Several of the IoC libraries will handle lifetime management for you.
(As always, there are exceptions, such as static math classes and C# extension methods.)
其他推荐答案
I'd argue the only difference is syntax: MySingleton.Current.Whatever() vs MySingleton.Whatever(). The state, as David mentioned, is ultimately "static" in either case.
EDIT: The bury brigade came over from digg ... anyhow, I thought of a case that would require a singleton. Static classes cannot inherit from a base class nor implement an interface (at least in .Net they cannot). So if you require this functionality then you must use a singleton.