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 {@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);//Show the string value defined by the private constructorToast.makeText(getApplicationContext(),Singleton.getInstance().getString(), Toast.LENGTH_LONG).show();//Change the string value and launch intent to ActivityBSingleton.getInstance().setString("Singleton");Intent intent = new Intent(getApplicationContext(),ActivityB.class);this.startActivity(intent);}}andpackage 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