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