use of Singleton mode (singleton)
This address: Http://blog.csdn.net/caroline_wendy
Singleton (Singleton) is a special Java class that allows a class to create only one instance when an instance is created.
How long the application can be stored in memory, and how long the singleton can exist, so keeping the list of objects in a singleton can keep the crime data in existence,
Regardless of activity, fragment, and their life cycle changes.
To create a singleton, you create a class with a private constructor and a Get () method , where the Get () method returns an instance.
If the instance already exists, the Get () method returns it directly, and if the instance does not exist, the get () method calls the construction method to create it.
such as code, save a unique array through singleton mode, call an array using the Getcrimes, Getcrime method.
Code:
Package Com.chunyu.android.criminalintent;import Android.content.context;import Java.util.arraylist;import java.util.uuid;/** * Created by Wangchenlong on 14-10-16. */public class Crimelab {private arraylist<crime> mcrimes; private static Crimelab Scrimelab; Private Context mappcontent; Private Crimelab (Context appcontent) {mappcontent = appcontent; Mcrimes = new arraylist<crime> (); Temporary for (int i=0; i<100; ++i) {Crime c = new Crime (); C.settitle ("Crime #" + i); c.setsolved (i%2 = = 0); Mcrimes.add (c); }} public static Crimelab get (Context c) {if (Scrimelab = = null) Scrimelab = new Crimelab (C.geta Pplicationcontext ()); return Scrimelab; } public arraylist<crime> Getcrimes () {return mcrimes; Public Crime getcrime (UUID ID) {for (Crime c:mcrimes) {if (C.getid (). Equals (ID)) return C; } return null; }}
How to use:
Mcrime = Crimelab.get (Getactivity ()). Getcrime (Crimeid);
first determine the context of the Singleton, in the call Getcrime, read out the specific crime.
Android-Using a singleton mode (singleton)