The Singleton
The Singleton design pattern can be seen as a special case of a Lazy Getter. Indeed, the Lazy Getter is the basic construct of a Singleton. Additional, the Singleton does not use a member variable, but a global (static) variable, so that any call to the class would return the same variable.
Why is this useful? Just imagine, You are developing an e-mail application with an address book function. Hence an address book can contain a lot of contacs, stored somehow in a data file that maybe need to be loaded by an SQLite database, this can take a few moments on initial data access. So when a user opens the address book the first time, the Laze Gette will cteate the address book object and load the contacts from SQLite. Now it is not that difficult to imagine, that the user may opens more than one e-mail window and writes some e-mails in those windows and every e-mail window is using the address book. To avoid multiple timespans for initially loading the contacts for each instance (and also to save memory ;) ), it would be better to use the already instantiated and loaded address book. And that's where the Singleton is used.
Java learn Example
public class AddressBook
{
// this private class var of own class is required
private static Singleton instance;
// constructor can be empty for this example
private AddressBook () {}
// this method could be used to maybe load the address book data
public initiate()
{
System.out.println("Called a member method.");
}
// public Getter will return the private instance (and initiate it, if neccessary)
public static AddressBook getInstance ()
{
if (AddressBook.instance == null)
AddressBook.instance = new AddressBook ();
return AddressBook.instance;
}
}
{
// this private class var of own class is required
private static Singleton instance;
// constructor can be empty for this example
private AddressBook () {}
// this method could be used to maybe load the address book data
public initiate()
{
System.out.println("Called a member method.");
}
// public Getter will return the private instance (and initiate it, if neccessary)
public static AddressBook getInstance ()
{
if (AddressBook.instance == null)
AddressBook.instance = new AddressBook ();
return AddressBook.instance;
}
}
After the implementation of the Singleton class, which will in fact have some more methods, You always will call its instance:
...
AddressBook.instance.initiate();
...
AddressBook.instance.initiate();
...
Kommentare
Kommentar veröffentlichen