Saturday, May 10, 2014

singleton pattern in Android

 A singleton in Java is a class for which only one instance can be created provides a global point of access this instance. The singleton pattern describe how this can be archived.
Singletons are useful to provide a unique source of data or functionality to other Java Objects. For example you may use a singleton to access your data model from within your application or to define logger which the rest of the application can use.

package com.example.singletone;
 
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;
 
public class ActivityA extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
 
//Show the string value defined by the private constructor
Toast.makeText(getApplicationContext(),Singleton.getInstance().getString(), Toast.LENGTH_LONG).show();
 
//Change the string value and launch intent to ActivityB
Singleton.getInstance().setString("Singleton");
Intent intent = new Intent(getApplicationContext(),ActivityB.class);
this.startActivity(intent);
}
}
and
package com.example. singletone;
 
public class Singleton {
private static Singleton mInstance = null;
 
private String mString;
 
private Singleton(){
mString = "Hello";
}
 
public static Singleton getInstance(){
if(mInstance == null)
{
mInstance = new Singleton();
}
return mInstance;
}
 
public String getString(){
return this.mString;
}
 
public void setString(String value){
mString = value;
}
}

No comments:

Post a Comment