Thursday, July 16, 2009

Singleton Java ME Forms

Some of the mobile forms contain only static elements, which are not interacting with the user. That kind of forms are usually aimed to provide a list of command items on them, which are redirecting users to other forms. So, it is reasonable to design that classess in singleton pattern. Aim of creating a form in singleton pattern is to ensure that a class has only one instance at a time. Instead of creating an instance of that kind of mobile forms each time, you can hide the constructor from global access and make it protected.
The instance that will represent the class is placed as a static field in the class and initialized when it is not created before.
import javax.microedition.lcdui.Form;

public class SingletonForm extends Form {

 private static SingletonForm instance;

 public static SingletonForm createNew() {
  if(instance == null){
   instance = new SingletonForm(""); 
  }
  return instance;
 }
 
 public void showNew() {
  MainMidlet.getInstance().getDisplay().setCurrent(this);
 }
 
 protected SingletonForm(String str){
  super(str);
  append("SingletonForm!");
 }
}


This is the 'not-thread-safe' version of singleton pattern. If you want it to be thread-safe then use locking. In order to call an instance of the above class you can type in your caller:
SingletonForm.createNew().showNew();

No comments:

Post a Comment