目的
Stringオブジェクトの不変リストとして使用するクラスを作成します。
アプローチ
単純な List < E>をCollections.unmodifiableList(List<? extends T> list)でラップするのではなく、Google GuavaのImmutableList<E>コレクションを活用することにしました。 >、ラップされていることを認識していません (ソース: ImmutableCollectionsExplained )。
要件
- スレッド間で使用される「値ホルダー」となるクラス
- 作成後に内部値を変更するコードを許可しないでください
あると便利なもの
- クラスは、作成順に値を反復するためにIterable<E>を実装する必要があります
- 指定されたStringのセットに対して、クラスは 1 つだけ存在する必要があります。
試み
より多くの組み合わせが可能ですが、ここでいくつかの試みを行います。ユーモラスな表現を許してください。
試み #1 (使用例を含む)
import java.util.List;
import com.google.common.collect.ImmutableList;
class BritnetSpearsSpellings implements Iterable<String> {
public static BritnetSpearsSpellings of(String... spellings) {
BritnetSpearsSpellings britneySpears = new BritnetSpearsSpellings();
britneySpears.spellings = ImmutableList.copyOf(spellings);
return britneySpears;
}
private List<String> spellings;
private BritnetSpearsSpellings() {
}
public List<String> getSpellings() {
return spellings;
}
}
@Override
public Iterator<String> iterator() {
return spellings.iterator();
}
public class Usage {
public static void main(String[] args) {
for (String sepllin : BritnetSpearsSpellings.of("Brittany Spears", "Brittney Spears", "Britany Spears"))
System.out.printf("You spel Britni like so: %s%n", sepllin);
}
}
}
試み #2
class BritnetSpearsSpellings implements Iterable<String> {
public static BritnetSpearsSpellings of(String... spellings) {
BritnetSpearsSpellings britneySpears = new BritnetSpearsSpellings();
britneySpears.spellings = ImmutableList.copyOf(spellings);
return britneySpears;
}
private ImmutableList<String> spellings;
private BritnetSpearsSpellings() {
}
public ImmutableList<String> getSpellings() {
return spellings;
}
@Override
public Iterator<String> iterator() {
return spellings.iterator();
}
}
試み #3
class BritnetSpearsSpellings implements Iterable<String> {
public static BritnetSpearsSpellings of(String... spellings) {
BritnetSpearsSpellings britneySpears = new BritnetSpearsSpellings(ImmutableList.copyOf(spellings));
return britneySpears;
}
private final ImmutableList<String> spellings;
private BritnetSpearsSpellings(ImmutableList<String> spellings) {
this.spellings = spellings;
}
public ImmutableList<String> getSpellings() {
return spellings;
}
@Override
public Iterator<String> iterator() {
return spellings.iterator();
}
}
相違点のまとめ
1 はList<E>をパブリック インターフェイスに保持し、JavaDoc で不変性を文書化します。
2 Google GuavaのImmutableList<E>としてすべてを保存および公開します
3 特殊なコンストラクターを作成することを犠牲にして、内部参照を final として保持します。他の初期化オプション (実際には実際のクラスにあります) がない場合、静的ファクトリ メソッドの初期化がばかげているように見える可能性があります。
質問
選択の背後にある理由とともに、これらの実装のいずれかを選択するのを手伝ってください。
アプローチ#2の主な欠点は、クライアントが特殊なGoogle Guavaタイプを認識/可視化する必要があり、おそらくすべきではないことだと思いますか?