java - example for Singleton pattern - Stack Overflow
Singleton pattern in java..
Singleton Class In Java With Examples: A Comprehensive Guide
What is an example of the singleton design pattern?
Videos
Factsheet
A "file" isn't a Java object (and java.io.File definitely isn't a singleton). I wouldn't think of files on disk as a singleton either - they're just shared resources. In particular, it's not like there's only one file on disk :)
A more common example of the singleton pattern is configuration - or logging. For example, LogManager.getLogManager returns "the" LogManager, and you can't create new ones. Likewise you might have one common configuration object which can be accessed statically. (In a dependency injected system the configuration may well not be a singleton, however - instead each component is provided the bits of configuration they need so that they don't have to fetch a "common" one.)
Yes, but only if all threads access the same file, and you are using a custom implementation (not java.io.File, perhaps a wrapper)
the singleton pattern is a design pattern that is used to restrict instantiation of a class to one object
Singletons (being often a bad choice) are classes that can have only one instance throughout the whole program.
For example a SingletonConfigFile might look like this. Have in mind that:
- it is for reading one file only. It would make sense for this to be a config file.
- if your class can be instantiated more than once, for different files, it is not singleton.
- don't use this code - it doesn't take into account concurrency problems which are a whole different area of discussion.
.
public SingletonConfigFile {
private static String filename = "config.xml";
private File file;
private static SingletonConfigFile instance;
private SingletonConfigFile() {
if (instance != null) {
throw new Error();
}
file = new File(filename);
}
public synchronized SingletonConfigFile getInstance() {
if (instance == null) {
instance = new SignletonConfigFile();
}
return instance
}
public String read() {
// delegate to the underlying java.io.File
}
}
But this example is on the edge of sense. Singletons are used in cases when there is only one object (as I stated above). For example it would make sense to have:
RingOfPower.getInstance()- there is only one ring of power (Sauron's), and there can't exist more.Sun.getInstance()- only one star called "sun".- all objects in the withing of your application that logically should exist only once - a registry, an application context, etc.
What is singleton pattern in java..? what advantage of use this.? why singleton pattern is used??. please explain me with real life example..