9
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Apex Design Patterns(Singleton)

Last updated at Posted at 2019-04-19

1.Singletonの概要

単一のトランザクションコンテキスト内で一度だけインスタンス化する。
ガバナー制限及びリソースの多重使用を避ける。

主なポイント:
 ・コンストラクタを private とする
 ・Singletonインスタンス変数宣言および初期化
 ・Singletonインスタンス取得用公開メソッド

UML構造図
image.png

2.実装例

Apex に static 変数の life cycle はトランザクションです。
java のように synchronized を考慮しなくても大丈夫です。

Singletonインスタンスの初期化は2つの方法があります。
  ・eager-initialization
  ・lazy-initialization

eager-initialization
public class Singleton {
    private static Singleton instance = new Singleton();
    private Singleton (){}

    public static Singleton getInstance() {
     return instance;
    }
}
lazy-initialization
public class Singleton {
    private static Singleton instance;
    private Singleton (){}

    public static Singleton getInstance() {
     if (instance == null) {
         instance = new Singleton();
     }
     return instance;
    }
}

3.参照資料

9
3
0

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
9
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?