How to use singleton mode in Android studio

Time:2022-5-5
catalogue
  • Singleton mode
  • Use of simple interest mode
  • Memory leak in Android

This article briefly introduces how to use singleton mode and precautions in Android studio.

Singleton mode

Why use singleton mode?

For some objects, we only need one, only one thread pool, cache, or only one printer, robot, and only one magnetic sensor on the robot. We can implement it through global static variables, but the creation of global variables at the beginning of the program may consume resources and may not be used all the time. Singleton mode is as convenient as global variables without its disadvantages.

Use of simple interest mode

public class Sensor {

  //Use static variables to record unique instances
  private static Sensor sensorInstance;

  /**
   *Private construction method
   */
  private Sensor(){}

  /**
   *Instantiation method
   * @return Sersor
   *Synchronized guarantees that no two threads will enter at the same time
   */
  public static synchronized Sensor getSersorInstance(){
    if(sensorInstance == null) {
       sensorInstance = new Sensor();
    }
    //Return unique instance of sensor
    return sensorInstance;
  }

}

However, if you want to create examples urgently, and the burden of example creation is not heavy.


public class Sensor {

  private static Sensor sensorInstance = new Sensor();

  private Sensor(){}

  public static Sensor getSersorInstance(){
    return sensorInstance;
  }
}

If many threads use getsersorinstance frequently, it may affect the performance. You can use double check locking

public class Sensor {

  //Volatile ensures that sensorinstance is initialized and processed correctly by multiple threads
  private volatile static Sensor sensorInstance;
  
  private Sensor(){}
  
  public static Sensor getSersorInstance(){
    //Check whether the sensorinstance exists. If it does not exist, enter the synchronization block
    
    if(sensorInstance == null) {
      //The code in the synchronization block will only be executed for the first time
      synchronized(Sensor.class) {
        if(sensorInstance == null) {
          sensorInstance = new Sensor();
        }
      }
    }
    return sensorInstance;
  }

}

Memory leak in Android

1. When instantiating, we often need to pass in some parameters, such as context

And then it goes smoothly into a chapter


Sensor sensor = Sensor.getSersorInstance(MainActivity.this);

Then there is a very serious problem. The sensor singleton holds the this object of mainactivity, so when we jump to other activity pages, the object of mainactivity still cannot be released and cannot be recycled.

So we should use the context in the application

2. Also in the urgent method


public class Sensor {

    public static final Sensor SENSOR_INSTANCE = new Sensor();
    private List<MyListener> mListenerList;

    private Sensor() {
      mListenerList = new ArrayList<MyListener>();
    }

    public static Sensor getInstance() {
      return SENSOR_INSTANCE;
    }

    public void registerListener(MyListener listener) {
      if (!mListenerList.contains(listener)) {
        mListenerList.add(listener);
      }
    }
    public void unregisterListener(MyListener listener) {
      mListenerList.remove(listener);
    }
  }

  interface MyListener {
    public void onSomeThingHappen();
  }

MainActivity:


public class MainActivity extends Activity {

    private MyListener mMyListener=new MyListener() {
      @Override
      public void onSomeThingHappen() {
      }
    };

    private Sensor sensor = Sensor.getInstance();
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      sensor.registerListener(mMyListener);
    }
}

Non static internal class (sensor) objects (mlistenerlist) will hold references to external class objects (mmylistener). Therefore, the external class object (mmylistener) is held in the same way and will not be recycled and memory leaks, so it is necessary to


@Override
  protected void onDestroy() {
    Sensor.unregisterListener(mMyListener);
    super.onDestroy();
  }

The above is the details of how to use singleton mode in Android studio. For more information about using singleton mode in Android studio, please pay attention to other relevant articles of developeppaer!

Recommended Today

Modify user information changeinfo

When judging the persistence layer: Problem: there is such a problem when modifying user information. For example: the user’s email is not required. It was not empty originally. At this time, the user deletes the mailbox information and submits it. At this time, if it is not empty to judge whether it needs to be […]