While reading the book “Programming for Android” by Brown Hardy, I ran into the following code. There is a singleton class:

public class CrimeLab { private static CrimeLab sCrimeLab; private Context mAppContext; public ArrayList<Crime> mCrimes; private CrimeLab (Context appContext){ mAppContext = appContext; mCrimes = new ArrayList<Crime>(); } public ArrayList<Crime> getCrimes() { return mCrimes; } public static CrimeLab get(Context c){ if (sCrimeLab == null){ sCrimeLab = new CrimeLab (c.getApplicationContext()); } return sCrimeLab; } } 

There is another class in which the CrimeLab class get and getCrimes methods are used:

 public class CrimeListFragment extends ListFragment { private ArrayList<Crime> mCrimes; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mCrimes = CrimeLab.get(getActivity()).getCrimes(); } } 

I am interested in this line of code mCrimes = CrimeLab.get(getActivity()).getCrimes(); . How do we access CrimeLab if we have not created an instance of the CrimeLab class, and only the sCrimeLab variable in CrimeLab is static? I can assume that the prefix s is not taken into account, or I strongly do not understand the principle of singletons.

  • Something tells me that the android has nothing to do with it - it will be the same on pure Java .. - Drakonoved
  • @Drakonoved Yes, perhaps, but just in case, I decided to clarify - Winter Fox

1 answer 1

s in this case is the designation of a static variable, but the name does not affect its essence, it can be anything.

The get method is also static.

The code says that if sCrimeLab is null , then you must create an instance of the class, otherwise the existing instance will be returned.

For good, you can divide the string mCrimes = CrimeLab.get(getActivity()).getCrimes(); on

 CrimeLab crimeLab = CrimeLab.get(getActivity()); mCrimes = crimeLab.getCrimes(); 
  • The principle of the work of the singlet class, I understood, but I still do not understand that line of code. It turns out that we are accessing the static get method, it creates and returns an instance of the CrimeLab class, then through the "." do we refer to its getCrimes method? - Winter Fox
  • @WinterFox added in reply - Komdosh Nov.