2 回答

TA貢獻1797條經(jīng)驗 獲得超6個贊
讓我們從值類型開始。它包含一個字符串表示和一個 Base 對象。(即,它有一個字符串表示和一個類似解碼器的東西)。為什么?因為我們不想傳遞我們需要查看并“猜測”它們是什么基礎(chǔ)的字符串。
public class CustomNumber {
private final String stringRepresentation;
private final Base base;
public CustomNumber(String stringRepresentation, Base base) {
super();
this.stringRepresentation = stringRepresentation;
this.base = base;
}
public long decimalValue() {
return base.toDecimal(stringRepresentation);
}
public CustomNumber toBase(Base newBase) {
long decimalValue = this.decimalValue();
String stringRep = newBase.fromDecimal(decimalValue);
return new CustomNumber(stringRep, newBase);
}
}
然后我們需要定義一個足夠廣泛的接口來處理任何常規(guī)或自定義符號庫。我們稍后會在上面構(gòu)建具體的實現(xiàn)。
public interface Base {
public long toDecimal(String stringRepresentation);
public String fromDecimal(long decimalValue);
}
我們都準備好了。在轉(zhuǎn)到自定義字符串符號之前,讓我們做一個示例實現(xiàn)以支持標準十進制數(shù)字格式:
public class StandardBaseLong implements Base{
public long toDecimal(String stringRepresentation) {
return Long.parseLong(stringRepresentation);
}
public String fromDecimal(long decimalValue) {
return Long.toString(decimalValue);
}
}
現(xiàn)在終于來到自定義字符串庫:
public class CustomBase implements Base{
private String digits;
public CustomBase(String digits) {
this.digits = digits;
}
public long toDecimal(String stringRepresentation) {
//Write logic to interpret that string as your base
return 0L;
}
public String fromDecimal(long decimalValue) {
//Write logic to generate string output in your base format
return null;
}
}
現(xiàn)在您有一個框架來處理各種自定義和標準基礎(chǔ)。
當然,可能會有更多的定制和改進的功能(更多方便的構(gòu)造函數(shù)、hashCode 和 equals 實現(xiàn)和算術(shù))。但是,它們超出了這個答案的范圍。
添加回答
舉報