Definitions
* One instance of a class or one value accessible globally in an application.
- Ensure a class has only one instance, and provide a global point of access to it.
- Encapsulated “just-in-time initialization” or “initialization on first use”.
Problem
Application needs one, and only one, instance of an object. Additionally, lazy initialization and global access are necessary.Where to use & benefits
- Ensure unique instance by defining class final to prevent cloning.
- May be extensible by the subclass by defining subclass final.
- Make a method or a variable public or/and static.
- Access to the instance by the way you provided.
- Well control the instantiation of a class.
- Define one value shared by all instances by making it static.
- Related patterns include
- Abstract factory, which is often used to return unique objects.
- Builder, which is used to construct a complex object, whereas a singleton is used to create a globally accessible object.
- Prototype, which is used to copy an object, or create an object from its prototype, whereas a singleton is used to ensure that only one prototype is guaranteed.
This is one of the most commonly used patterns. There are some instances in the application where we have to use just one instance of a particular class. Let’s take up an example to understand this.
A very simple example is say Logger, suppose we need to implement the logger and log it to some file according to date time. In this case, we cannot have more than one instances of Logger in the application otherwise the file in which we need to log will be created with every instance.
We use Singleton pattern for this and instantiate the logger when the first request hits or when the server is started.
package creational.singleton; import org.apache.log4j.Priority; import java.text.SimpleDateFormat; public class Logger { | ||
| private String fileName; private Properties properties; private Priority priority; /** /** /** // singleton - pattern | |
}// End of class |
Difference between static class and static method approaches:
One question which a lot of people have been asking me. What’s the difference between a singleton class and a static class? The answer is static class is one approach to make a class “Singleton”.
We can create a class and declare it as “final” with all the methods “static”. In this case, you can’t create any instance of class and can call the static methods directly.
Example:
final class Logger {
//a static class implementation of Singleton pattern
static public void logMessage(String s) {
System.out.println(s);
}
}// End of class
//==============================
public class StaticLogger {
public static void main(String args[]) {
Logger.logMessage("This is SINGLETON");
}
}// End of class
The advantage of this static approach is that it’s easier to use. The disadvantage of course is that if in future you do not want the class to be static anymore, you will have to do a lot of recoding.
No comments:
Post a Comment