Skip to content
This repository was archived by the owner on Dec 30, 2023. It is now read-only.

Commit ea393ce

Browse files
committed
[Enhancement] Add Singleton pattern
1 parent 973b0ec commit ea393ce

File tree

3 files changed

+40
-0
lines changed

3 files changed

+40
-0
lines changed
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package designpattern.singleton;
2+
3+
public class Configure {
4+
// クラスのロード時に1度だけ初期化を実行
5+
private static Configure instance = new Configure();
6+
7+
// Configureクラス以外からコンストラクタを呼び出すことを禁止
8+
private Configure() {
9+
System.out.println("インスタンスを生成しました。");
10+
}
11+
12+
public static Configure getInstance() {
13+
return instance;
14+
}
15+
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package designpattern.singleton;
2+
3+
public class Main {
4+
public static void main(String[] args) {
5+
System.out.println("Start.");
6+
7+
Configure configure1 = Configure.getInstance();
8+
Configure configure2 = Configure.getInstance();
9+
10+
if (configure1 == configure2) {
11+
System.out.println("同じインスタンスです。");
12+
} else {
13+
System.out.println("同じインスタンスではありません。");
14+
}
15+
16+
System.out.println("End.");
17+
}
18+
}
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
/**
2+
* Singleton パターン
3+
*
4+
* - 指定したクラスのインスタンスが絶対に1個しか存在しないことを保障したい
5+
* - インスタンスが1個しか存在しないことをプログラム上で表現したい
6+
*/
7+
package designpattern.singleton;

0 commit comments

Comments
 (0)