Datasheet

26
Part I: Getting Started on BlackBerry Apps
The simplest example of a software pattern that you might use is one I
employ in a great many of my applications: the Singleton pattern. Only one
instance of a singleton class will exist in an application. Most singleton
classes have the general appearance shown in Listing 1-1.
Listing 1-1: The Smallest Form of a Singleton Pattern, Implemented in Java
public class SingletonClass
{
private static SingletonClass m_instance;
public static SingletonClass getInstance()
{
if (null == m_instance)
{
m_instance = new SingletonClass();
}
return (m_instance);
}
private SingletonClass()
{
// initialization code
}
//
// the remainder of the methods
//
}
Any code that makes use of this SingletonClass will execute Singleton
Class.getInstance(). This method will instantiate (create) and initialize
the solitary instance of this class available for the application the first time
the method is called, and return that instance that time and every subsequent
time the method is called.
Your application can make use of the Singleton pattern when you want to
restrict access to one specific location for information. This pattern comes in
useful for a large number of different parts of an application, such as
User settings: You will normally have only one user of your application,
and so storing that user’s preferences for your application in a
singleton class makes perfect sense.
Resource connections: Access to resources such as a database should
be funneled through one object because opening a connection to a
resource usually requires substantial code execution. Opening the
connection once and maintaining it through your application’s lifetime
incurs less overhead than multiple openings and closings. You can use a
singleton class to ensure that a connection is opened only once.
05_467114-ch01.indd 2605_467114-ch01.indd 26 8/30/10 1:05 PM8/30/10 1:05 PM