[英]Java Class Immutable with Thread Safe Collection
假設我有以下課程:
public final class Person {
final private String personFirstName;
final private String personLastName;
final private ConcurrentMap<Double, String> phoneMessages;
public Person(String firstname, String lastname) {
phoneMessages = new ConcurrentHashMap<Double, String>();
this.personFirstName = firstname;
this.personLastName = lastname;
}
public void add(Double key, String item) {
phoneMessages.put(key, item);
}
public String getPersonFirstName() {
return personFirstName;
}
public String getPersonLastName() {
return personLastName;
}
}
即使我創建了一個帶有私有最終線程安全集合的類,但我的類是不可變的嗎? 我的猜測不是。
如果在對象中沒有集合是不正確的做法,那么Java中的正確做法是什么? 我將如何設計包含集合的類?
正如其他人指出的那樣, 如何使用您的類將確定使其不可變是否合適。
也就是說,您的Person
類的此版本是不可變的:
public final class Person {
final private String personFirstName;
final private String personLastName;
final private ConcurrentMap<Double,String> phoneMessages;
public Person(String firstname, String lastname) {
this.phoneMessages = new ConcurrentHashMap<Double,String> ();
this.personFirstName = firstname;
this.personLastName = lastname;
}
private Person(String firstname, String lastname, ConcurrentHashMap<Double,String> phoneMessages) {
this.personFirstName = firstname;
this.personLastName = lastname;
this.phoneMessages = phoneMessages;
}
public Person add(Double Key, String item){
ConcurrentHashMap<Double, String> newMap = new ConcurrentHashMap<>(this.phoneMessages);
newMap.put(Key, item);
return new Person(this.personFirstName, this.personLastName, newMap);
}
public String getPersonFirstName() {
return personFirstName;
}
public String getPersonLastName() {
return personLastName;
}
public Map<Double, String> getPhoneMessages() {
return Collections.unmodifiableMap(this.phoneMessages);
}
}
注意, add
方法返回一個不同的Person
實例,以便當前的Person
實例保持不變(不可變)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.