20130303 singleton 問題
結城さんのデザインパターン入門5章のsingletonの問題5-2より。
●問題5-2
インスタンスの個数が3個に限定されているクラスTripleを作ってください。インスタ
ンスには0,1,2という番号がついており、getlnstance(inti d)でid番のインスタン
スが得られるものとします。
下記の通り、コーディング。
■Tripleクラス
public class Triple {
private static Triple triples = {
new Triple(),
new Triple(),
new Triple()
};
private Triple(){
System.out.println("インスタンスが作られました");
}
public static Triple getInstance(int id){
if(id < 0 || id > 2){
System.out.println("idは0から2の範囲にしてください。");
return null;
}
return triples[id];
}
}
■Mainクラス
public class Main {
/**
* @param arg
*/
public static void main(String args) {
System.out.println("Start.");
for(int i = 0; i < 3; i++ ){
if(Triple.getInstance(i) == null){
System.out.println("インスタンは作られませんでした。");
}
}
}
}
<実行結果>
--------------------------------
Start.
インスタンスが作られました
インスタンスが作られました
インスタンスが作られました
--------------------------------
回答は下記の通り。
■Tripleクラス
public class Triple {
private static Triple triple = new Triple{ // newを書いた方がいいかな。
new Triple(0), // 引数無しのコンストラクタを定義せず、引数があるコンストラクタだけ記述した場合にもデフォルトのコンストラクタは作成されないため、引数無しでそのクラスのオブジェクトを作成する事が出来なくなりますので注意して下さい。
new Triple(1),
new Triple(2),
};
private int id;
private Triple(int id) { // コンストラクタにidを指定。
System.out.println("The instance " + id + " is created.");
this.id = id;
}
public static Triple getInstance(int id) {
return triple[id];
}
public String toString() { // あるとあとあと便利かな
return "[Triple id=" + id + "]";
}
}
■Mainクラス
public class Main {
public static void main(String[] args) {
System.out.println("Start.");
for (int i = 0; i < 9; i++) { // とりあえず3より多くつくって試すべきだったかな。
Triple triple = Triple.getInstance(i % 3);
System.out.println(i + ":" + triple);
}
System.out.println("End.");
}
}
<実行結果>
----------------------------
Start.
The instance 0 is created.
The instance 1 is created.
The instance 2 is created.
0:[Triple id=0]
1:[Triple id=1]
2:[Triple id=2]
3:[Triple id=0]
4:[Triple id=1]
5:[Triple id=2]
6:[Triple id=0]
7:[Triple id=1]
8:[Triple id=2]
End.
-------------------------------------