2 回答
![?](http://img1.sycdn.imooc.com/533e4c0500010c7602000200-100-100.jpg)
TA贡献1797条经验 获得超6个赞
让我们从值类型开始。它包含一个字符串表示和一个 Base 对象。(即,它有一个字符串表示和一个类似解码器的东西)。为什么?因为我们不想传递我们需要查看并“猜测”它们是什么基础的字符串。
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);
}
}
然后我们需要定义一个足够广泛的接口来处理任何常规或自定义符号库。我们稍后会在上面构建具体的实现。
public interface Base {
public long toDecimal(String stringRepresentation);
public String fromDecimal(long decimalValue);
}
我们都准备好了。在转到自定义字符串符号之前,让我们做一个示例实现以支持标准十进制数字格式:
public class StandardBaseLong implements Base{
public long toDecimal(String stringRepresentation) {
return Long.parseLong(stringRepresentation);
}
public String fromDecimal(long decimalValue) {
return Long.toString(decimalValue);
}
}
现在终于来到自定义字符串库:
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;
}
}
现在您有一个框架来处理各种自定义和标准基础。
当然,可能会有更多的定制和改进的功能(更多方便的构造函数、hashCode 和 equals 实现和算术)。但是,它们超出了这个答案的范围。
添加回答
举报