I've searched about this here and on StackOverflow and found some differences between the two.But I'm still not sure in what cases one would prefer a Singleton, and in what cases one would choose to use a static class.(In languages which don't support 'static classes', like Java, I'm obviously referring to classes containing only static methods and fields).Please give me concrete examples of cases where you would pick each one, and explain why.
When to use a Singleton and when to use a static class
object oriented;singleton;static
A case where a static class might be a good idea is when you want to collect related pieces of functionality, but you don't need to have any internal state in any object. An example could be the Math class in Java. It contains a whole bunch of related functions that are accessed outside the context of any specific object instance. I've done similar things where a set of common utility functions that are used in multiple places in an application are grouped together into a single utility class.A singleton is used when you do want an actual object (with its own internal state and everything), and you want to limit your system to exactly one instance of that object. This might be useful if you have some kind of shared resource, such as a database, an in-memory cache, or maybe some specialized piece of hardware like a robotic arm. Many parts of your program might want to use this resource and you might want to have all access to the resource go through a single point. A singleton isn't always the only way to handle these situations, but it's one of the few places I think a singleton might be a good choice.