생성 된 클래스의 모든 인스턴스를 저장하는 정적 arraylist를 가진 Coin 클래스를 만들고 있는데, 초기 인스턴스로 그 목록을 초기화해야합니다. 어떻게해야하는지 알지 못했습니다. 중복 된 코드로 인해 두 번 추가하지 않고 할 수 있습니다. 제안 사항은 무엇입니까?초기 값을 가진 클래스의 인스턴스를 가진 정적 arraylist
public class Coin {
private static ArrayList<String> coinNames = new ArrayList<>();
private static ArrayList<String> coinAbbreviations = new ArrayList<>(Arrays.asList("CLP"));
private static ArrayList<Coin> coins =
new ArrayList<>(Arrays.asList(new Coin("Pesos chilenos", "CLP", 1f, "CLP")));
private static HashMap<String,Float> exchangeRates;
private String coinName;
private String coinAbbreviation;
private Float coinValue;
private String unit;
public Coin(String coinName, String coinAbbreviation, Float coinValue, String unit) {
assert !coinAbbreviations.contains(coinAbbreviation) : "Coin abbreviation already used";
assert coinAbbreviations.contains(unit) : "Coin unit non existent.";
assert !coinNames.contains(coinName) : "Coin name already used.";
this.coinName = coinName;
this.coinAbbreviation = coinAbbreviation;
this.coinValue = coinValue;
this.unit = unit;
coins.add(this);
}
}
* 정적 ArrayList에 *가 아니라이 패턴이 있음을 유의하시기 바랍니다 – Ravi
을하려고 무엇인지 본질적으로 스레드 안전하지 않은 (즉, 기본적으로 thread-safe 코드를 만들 수는 없습니다.), 그렇게하는 것은 나쁜 습관입니다. 보다 나은 접근법은 사적 생성자와 그 생성자를 호출하고 그 인스턴스를'coins'에 추가하는 정적 팩토리 메소드입니다. – yshavit
Coin 인스턴스를 생성 (및 반환)하는 CoinFactory 클래스를 만들어 자신에게 추가하는 것이 더 낫습니다. 현재 솔루션은 스레드로부터 안전하지 않으며 단지 단점 일뿐입니다. – DodgyCodeException