java - When to use a Singleton and when to use a static class - Software Engineering Stack Exchange
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.
Read full article from java - When to use a Singleton and when to use a static class - Software Engineering Stack Exchange
No comments:
Post a Comment