Where should I put global methods and variables in an Android app?

When I write a method or use a member variable, I often find that I need to share it in the application. But where should they go?

I can subclass Activity, but it crashes as soon as I use MapView and I have to use MapActivity, so not all of my actions are inherited from my subclass. Do I have it?

If inheritance is not applicable, I tend to put common methods and member variables in a subclass of the Application object, but I find that this creates a mess of code, since each class must either access the application object through the context, or I must pass it.

I suspect that I would be better off creating MyApplication.getInstance () and saving everything in singleton mode, instead of passing the application object down through the application classes. but before I wanted to see what you guys had to say.

+3
source share
3 answers

If you want to access the β€œGlobal singleton” outside the scope of the action, and you do not want to pass Contextthrough all the involved objects to receive a Singleton, you can simply define, as you described, a static attribute in your application class that contains a reference to itself. Just initialize the attribute in the method onCreate().

For instance:

public class ApplicationController extends Application {
    private static ApplicationController _appCtrl;

    public static ApplicationController getAppCtrl()
    {
         return _appCtrl;
    }
}

: Application , , , , :

public static Resources getAppResources()
{
    return _appCtrl.getResources();
}
+5

Util . , , .

+2

:

Android?

. singleton - , . , , , . , . , , .

, , , playTurn(), :

public void playTurn() {
   globalPlayer.incrementClock();
   globalPlayer.doSomething();
   globalPlayer.doSomethingElse();
}

, . , playTurn() , globalPlayer. , . , . , :

public void playTurn(Player player) {
   player.incrementClock();
   player.doSomething();
   player.doSomethingElse();
}

:

playTurn( player1 );
playTurn( player2 );

playTurn() player1 player2, . .

- , - . , , . , . ,

public class Game {
   Player player1;
   Player player2;
   Board board;

   public void startGame() {
      BlueTooth blueTooth = BlueTooth.getChannel();

      player1 = new LocalPlayer();
      player2 = new NetworkedPlayer( blueTooth );

      board = new Board();

      player1.setOpponent( player2 );
      player1.setBoard( board );
      player2.setOpponent( player1 );
      player2.setBoard( board );
  }
}

, . 1 , , 2 , . , , , , , , , .

, , , , . , PlayerManager, , Player . PlayerManager - , , .

, , . , , . , .

0

Source: https://habr.com/ru/post/1777787/


All Articles