專案需將 C# 核心領域模型 `UnitScalarTypeRelation` 移植至 Java 平台。原始碼大量使用屬性、列舉與泛型集合,需對應至 Java Bean 慣例與 Collections Framework。
public class UnitScalarTypeRelation
{
// 回傳單位型別,如 Area、Volume
public string ReturnType { get; set; }
// 子元素順序:AscOrder(固定首項) / DisOrder(任意順序)
public SubElementType SubTypeType = SubElementType.AscOrder;
// 參與運算的單位參數清單,如 [Length, Time]
public List<string> UnitParaType { get; set; }
}
public enum SubElementType {
AscOrder, // A,(B|C|D) 首項固定,其餘任意
DisOrder, // 完全無序
Combination // 組合模式
}
import java.util.List;
import java.util.ArrayList;
public class UnitScalarTypeRelation {
private String returnType;
private SubElementType subTypeType = SubElementType.AscOrder;
private List<String> unitParaType = new ArrayList<>();
// Getter / Setter
public String getReturnType() { return returnType; }
public void setReturnType(String returnType) { this.returnType = returnType; }
public SubElementType getSubTypeType() { return subTypeType; }
public void setSubTypeType(SubElementType subTypeType) { this.subTypeType = subTypeType; }
public List<String> getUnitParaType() { return unitParaType; }
public void setUnitParaType(List<String> unitParaType) { this.unitParaType = unitParaType; }
// 建構子
public UnitScalarTypeRelation() {}
public UnitScalarTypeRelation(String returnType, SubElementType subTypeType, List<String> unitParaType) {
this.returnType = returnType;
this.subTypeType = subTypeType;
this.unitParaType = unitParaType;
}
// 方便除錯
@Override
public String toString() {
return "UnitScalarTypeRelation{" +
"returnType='" + returnType + '\'' +
", subTypeType=" + subTypeType +
", unitParaType=" + unitParaType +
'}';
}
}
原始需求提到「加法方法」與「長除速」型別關系,建議在 Java 中以靜態工廠或策略模式實現:
// 單位運算策略介面
public interface UnitOperation {
String getName(); // "Add", "Divide"
String apply(List<String> units); // 回傳結果單位
}
// 具體策略:長度 ÷ 速度 = 時間
public class LengthDivideSpeed implements UnitOperation {
public String getName() { return "長除速"; }
public String apply(List<String> units) {
// units[0]=Length, units[1]=Speed => 回傳 Time
return "Time";
}
}
// 註冊表:對應 C# Dictionary<string, Method>
public class UnitRelationRegistry {
private static final Map<String, UnitOperation> MAP = new HashMap<>();
static {
MAP.put("長除速", new LengthDivideSpeed());
// MAP.put("加法", new AddOperation());
}
public static UnitOperation get(String name) { return MAP.get(name); }
}
| C# 特性 | Java 對應 | 注意事項 |
|---|---|---|
| auto-property | private field + getter/setter | 加入建構子、toString、equals/hashCode |
| List<string> | List<String> (ArrayList) | 初始化避免 NullPointer |
| enum | enum class | Java enum 可攜帶方法與欄位 |
| Dictionary<K,V> | Map<K,V> (HashMap) | 執行緒安全考慮 ConcurrentHashMap |
| method group / delegate | Functional Interface / Lambda | Java 8+ 支援方法參考 `Class::method` |
核心資料模型遷移相對直觀,關鍵在於行為邏輯(運算規則、驗證)的重構。建議搭配單元測試驗證 `UnitRelationRegistry` 註冊與查詢正確性,並善用 Lombok `@Data` 簡化 Bean 程式碼。