LoginSignup
40
31

More than 3 years have passed since last update.

AndroidでSingletonを使っていいのか

Last updated at Posted at 2018-07-31

結論

「Android Singleton」で検索すると、Singletonを使うなという記事がたくさん出てきます。
しかし、公式のAndroid Developersには以下の通り「ほとんどのケースでは、Applicationのサブクラスを作るよりも、static Singletonの方がいい」と書いてあるので、使って大丈夫です。

Android Developers: Application
Note: There is normally no need to subclass Application. In most situations, static singletons can provide the same functionality in a more modular way. If your singleton needs a global context (for example to register broadcast receivers), include Context.getApplicationContext() as a Context argument when invoking your singleton's getInstance() method.

参考情報

I prefer singletons over Application because it helps keep an app much more organized and modular -- instead of having one place where all of your global state across the app needs to be maintained, each separate piece can take care of itself. Also the fact that singletons lazily initialize (at request) instead of leading you down the path of doing all initialization up-front in Application.onCreate() is good.

シングルトン(staticオブジェクト)のように、その寿命がApplicationの寿命と同じである場合、ApplicationContextを渡すのが望ましい

40
31
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
40
31