Singleton Pattern
It’s often situation when we write an application code that is we need only one object for several class in an application. For example, an application that working with database should be has only one Database Connection, only one object shared throughout the application. For this case we need a class design pattern which create an object once and share an instance of the object across the entire application.
So, how to create an singleton class? before we write singleton class, let’s take a look to the class bellow, say MyConnection class:
package belajarjavadotcom.post.singleton; public class MyConnection { private static MyConnection connection = new MyConnection(); private MyConnection() { } public static MyConnection getConnection() { return connection; } }
We need to get connection object to create a connection to database, but connection field in MyConnection class has been set as private but it’s static. So, the only way get reference to MyConnection object is make a call to the static method, that is getConnection(). It will look like this
MyConnection.getConnection();
This is the problem, when client calls MyConnection.getConnection() multiple times. Every call of method, create new object of class. We do not wish it will work in that way. So to ensure that class does not create a new object and clients still use the same instance of object. (more…)




