Singleton design pattern in JavaSingleton Pattern says that just"define a class that has only one instance and provides a global point of access to it". In other words, a class must ensure that only single instance should be created and single object can be used by all other classes. There are two forms of singleton design pattern
Advantage of Singleton design pattern
Usage of Singleton design pattern
Uml of Singleton design patternHow to create Singleton design pattern?To create the singleton class, we need to have static member of class, private constructor and static factory method.
Understanding early Instantiation of Singleton PatternIn such case, we create the instance of the class at the time of declaring the static data member, so instance of the class is created at the time of classloading. Let's see the example of singleton design pattern using early instantiation. File: A.java Understanding lazy Instantiation of Singleton PatternIn such case, we create the instance of the class in synchronized method or synchronized block, so instance of the class is created when required. Let's see the simple example of singleton design pattern using lazy instantiation. File: A.java Significance of Classloader in Singleton PatternIf singleton class is loaded by two classloaders, two instance of singleton class will be created, one for each classloader.Significance of Serialization in Singleton PatternIf singleton class is Serializable, you can serialize the singleton instance. Once it is serialized, you can deserialize it but it will not return the singleton object. To resolve this issue, you need to override the readResolve() method that enforces the singleton. It is called just after the object is deserialized. It returns the singleton object. Understanding Real Example of Singleton Pattern
Assumption: you have created a table userdata that has three fields uid, uname and upassword in mysql database. Database name is ashwinirajput, username is root, password is ashwini. File: JDBCSingleton.java File: JDBCSingletonDemo.java OutputNext TopicPrototype Design Pattern |