- Singleton pattern is one of the simplest design patterns in Java.This pattern provides one of the best ways to create an object.
- The Singleton's purpose is to control object creation, limiting the number of obejcts to one only.
- Since there is only one Singleton instance, any instance fields of a Singleton will occur only once per class, just like static fields.
- Singletons often control access to resources such as database connections or sockets.
Example : Whenever you create database in android sqlite, use Sigleton pattern for initialize database class object to avoid # of creation of database object and database object leak problem.
//This method will return single database object at a time to use
public static DatabaseHandler getInstance(Context context) {
if (mInstance == null) {
mInstance = new DatabaseHandler(context);
}
return mInstance;
}
//Now use like this in any activity where you want to initialize database object
dbHandler = DatabaseHandler.getInstance(this);
* This will create new database object or return if already exist in memory.
Comments
Post a Comment
Thanks, I'll respond you soon!