标签云

微信群

扫码加入我们

WeChat QR Code

What real (i.e. practical) difference exists between a static class and a singleton pattern?Both can be invoked without instantiation, both provide only one "Instance" and neither of them is thread-safe. Is there any other difference?


Depending on the language implementation and your usage patterns, a Singleton might be less efficient due to the overhead of calling the getInstance() method each time you want to use it (although probably in most cases it doesn't matter).

2019年10月20日00分56秒

There are lot of answers already. It is actually a singleton object where static methods are just functions, a non-OO entity.

2019年10月20日00分56秒

Depends upon the implemenation.. csharpindepth.com/Articles/General/Singleton.aspx

2019年10月20日00分56秒

There is a difference when you you want to allow third parties to supply the implementation of the class.In this case you usually need a Factory patterns as well.See agiletribe.wordpress.com/2013/10/08/…

2019年10月20日00分56秒

IMO this answer sums it up very well stackoverflow.com/questions/14097656/…

2019年10月20日00分56秒

Well, if you prefer it, neither is inherently threadsafe, you have to make them be threadsafe, both of them, so no difference there.

2019年10月20日00分56秒

Can you give an example of something which is inherently threadsafe, other than immutable types?

2019年10月20日00分56秒

To Skeet: People saying that singleton isn't threadsafe mean that a singleton is shared between threads unnecessarily all the time, while stack objects get shared when you need them to, which means you don't have to do unneeded synchronization.

2019年10月20日00分56秒

Geek: Imagine the singleton implements an interface Foo, and you have a method taking a Foo as a parameter. With that setup, callers can choose to use the singleton as the implementation - or they could use a different implementation. The method is decoupled from the singleton. Compare that with the situation where the class just has static methods - every piece of code which wants to call those methods is tightly coupled to the class, because it needs to specify which class contains the static methods.

2019年10月20日00分56秒

AmirBareket: It's not a singleton according to the singleton design pattern though - if the class itself allows multiple instances to be created, it's not a singleton IMO, regardless of what the factory does.

2019年10月20日00分56秒

Why would you pass a Singleton as a parameter, though, if you can access the same instance from just about anywhere by calling the static getInstance() method?

2019年10月20日00分56秒

HenriqueOrdine So it can fit into existing code and provide an interface?

2019年10月20日00分56秒

HenriqueOrdine They are speaking about static class, not a class with static methods. Static class cannot be instantiated. Nevertheless, if you pass an instance of a (non-static)class that contains static methods, you cannot call static methods on an instance.

2019年10月20日00分56秒

What's a static class? At least in Java, there's no such thing.

2019年10月21日00分56秒

Goran I was initially very confused by your wording. You said "you cannot call static methods on an instance". I read that as "if you have a reference to an instantiated object, you cannot call any static methods it may have." That is of course, incorrect. After reading it again a few times I think you meant "from inside static methods you cannot access non-static objects in the class" which is correct.Want to clarify that for anyone new to these concepts who comes across this answer and reads your comments.

2019年10月20日00分56秒

The second statement is wrong. We can't clone Singleton object. Singleton implementation must refuse this. If you really can clone Singleton, it's not Singleton.

2019年10月20日00分56秒

This is answer is not correct for Java: neither the singleton nor the static uses the stack.

2019年10月20日00分56秒

#1 is not important.#2 describes a defective implementation.#3 is completely unjustifiable.

2019年10月20日00分56秒

How can static object be stored in stack? New stack frame is created when you invoke a method, it stores method's local variables, this stack frame is removed when the method returns, and those local variables are lost. Sure stack is fast, but it is not suitable to store static objects.

2019年10月20日00分56秒

I cannot understand the number of upvotes on this one. 1) Why should Singleton have to be stored in stack? In managed languages like C# or Java data is stored in a managed heap, except for local method variables/parameters. 2) If you can clone it, then it's not a properly implemented singleton. 3) Singleton is known as a OOP anti-pattern; i.e. something that you should avoid if possible. 4) This is the only thing that's correct.

2019年10月20日00分56秒

+1 for good, pragmatic points.Singleton pattern is overused in general, but there are a few situations where it is fitting.See also:agiletribe.wordpress.com/2013/10/08/…

2019年10月20日00分56秒

+1 for pointing out eager initialization of static classes.

2019年10月20日00分56秒

You are right about advantage of being polymorphic. This is the most important point

2019年10月20日00分56秒

Nested static class can implement interface. Try coding it, will work. I could compile the code without any error.

2019年10月21日00分56秒

Why should static classes not do anything which needs to save state?

2019年10月20日00分56秒

Trisped: You have neither precise control over initialization nor finalization.

2019年10月20日00分56秒

Jon skeet has answered well. Its not good difference point.

2019年10月20日00分56秒

you lost me at "Singleton is my favorite pattern". Singleton is such a sharp corner that it should be considered an anti-pattern as well as a pattern. Classes can well have static states, that's also single access, if anything static state is more "single access" than singletons because most singleton implementations are broken ie. you can clone the singleton, while static is blessed by the definition to be unique.

2019年10月20日00分56秒

KyleDelaney: Simply State is the combination of different properties of an object which usually change over time. You can Google for formal definition.

2019年10月20日00分56秒

Static classes do have constructors: msdn.microsoft.com/en-us/library/k9x6w0hc.aspx

2019年10月21日00分56秒

Yes, static can have constructor which is internal to that class. This gets invoked when any static method in the class is called.

2019年10月20日00分56秒

For singleton on compile time, it is stored in the HEAP memory but if it gets instantiated once does it get stored in STACK?

2019年10月20日00分56秒

Luminous_Dev No. Any singleton instance is an object instance at the end of the day. It will get stored on heap without doubt.

2019年10月20日00分56秒

rahulmr Important distinction: the constructor also gets invoked before the first (AKA only) instance is created.

2019年10月21日00分56秒

polymorphism doesn't come into play with singletons at all

2019年10月21日00分56秒

So you think. I think differently. ;) For instance, imagine a singleton factory that returns an interface. You know you're getting an ISingleton (and it's the same one forever) but not necessarily which implementation.

2019年10月21日00分56秒

Nested static class can have instance methods as well, its not restricted to have only static methods.. Code it and you can see.

2019年10月21日00分56秒

In languages with a nicer object model (e.g. Ruby), classes are objects too. The "purely procedural" aspect of a static class is an arbitrary restriction imposed by the language.

2019年10月20日00分56秒

It's not really a singleton pattern, looks more like factory to me.

2019年10月20日00分56秒

Not really, the fundamental difference between the two is that the Singleton will "cache" its single object and keep returning (a reference to) the same one. The Factory pattern will create new instances.

2019年10月20日00分56秒

Then it's proxy-singleton :)

2019年10月20日00分56秒

Hmm, I know this variety of the Singleton as MonoState.

2019年10月20日00分56秒

example is factory pattern

2019年10月20日00分56秒

I don't think you can directly mock a singleton.Wouldn't you have to declare an interface that the singleton and the mock class both implement?

2019年10月20日00分56秒

espertus Why cant you mock your singleton? Example using mockito MySingleton mockOfMySingleton = mock(MySingleton.class).

2019年10月20日00分56秒

you're right, you can mock it with tools like mockito that use reflection.I meant that you can't mock it directly by subclassing it and overriding its methods.

2019年10月20日00分56秒

espertus Why not? When you instantiate the object you are testing you can substitute the subclass implementation of your singleton wherever you would have used the original. Ex: new ClazzToTest(mockSingleton);

2019年10月20日00分56秒

I haven't used Mockito, but how can you subclass a class that has a private constructor, which is the case for singletons, except by using reflection?Related discussions: stackoverflow.com/questions/2302179/mocking-a-singleton-class stackoverflow.com/questions/15939023/…

2019年10月20日00分56秒

I don't know about java, but in .Net, your last two points are incorrect.Static classes can reference static properies and fields, so on state they are equal.And they are lazy loaded -- the static constructor is run when:1) An instance of the class is created. 2) Any of the static members of the class are referenced.1 doesn't apply, which leaves 2.So, a static class is not loaded until the first time it is used.

2019年10月20日00分56秒

For static class, though you can't override the static method, you can hide the static method from its parent.

2019年10月20日00分56秒

if Animal animal = new Cat(); then animal.foo(); what happens?

2019年10月20日00分56秒

jmoreno static class is not loaded until the first time use? I believe it is stored in the stack memory on compile time. And it is instantly accessed.. isnt it?

2019年10月20日00分56秒

Luminous_Dev: at least for .net, a static class has a constructor that runs when first accessed, so no it is not instantly accessible.The static constructor could in theory take an unbounded amount of time.Where it (or any other class is stored) is an implementation detail, that is not really relevant to this question.

2019年10月20日00分56秒

Yes, everyone else seems to ignore the fact that a class with static methods can also have private static fields which it can still use to maintain state (and expose some of them to the client code via public static setters/getters).

2019年10月20日00分56秒

Static class can be very much instantiated in java . Read docs.oracle.com/javase/tutorial/java/javaOO/nested.html . Also refer my answer stackoverflow.com/a/37114702/1406510

2019年10月21日00分56秒

That's now not thread safe, and generally nasty in terms of how you access the interface implementation. Sure, having an interface is nice for testability - but then why bother with a singleton? Just avoid having a singleton at all; have one class implementing it for production purposes, one implementation for test purposes, and inject the right instance depending on what you're doing. No need to couple the singleton to its callers at all.

2019年10月21日00分56秒

thanks for the feedback. it is very simple to make it thread safe. in addition ,i use singleton for caching purpose.

2019年10月20日00分56秒

Yes, although with pointless overhead. Again, it's just simpler not to use a singleton.

2019年10月20日00分56秒

Nested static class can very much implement interface in java. Your second point is Wrong.

2019年10月21日00分56秒

I would brush it up for english grammar, but otherwise, it is an interesting read :)

2019年10月20日00分56秒

So if application exits will Singleton still remain in memory?

2019年10月20日00分56秒

I think you mean when your current thread exits, not the application, right? If the application exits, there's no way for another thread to use anything from it.

2019年10月20日00分56秒