java - 提取 boolean 值或字符串的接口(interface)

标签 java software-design

所以我有一个数据类,其布局如下:

class MyData {
  String str1,str2,str3;
  Boolean bool1,bool2;
}

属性将根据字符串输入填充,例如:

public void populate(String s) {
  if(s.contains("somevalue") myData.setStr1("xxx");
  if(s.constains("something else") myData.setBool1(true);
  else myData.setBool1(false);
}

当然,这是一种非常可怕的方法,因为 s.contains 实际上是一些非常棘手的条件,所以我定义了一个接口(interface):

public interface DataFinderInterface {
    public String findStringData(final String input);
    public Boolean findBooleanData(final String input);
}

因此 populate 方法可以重写为:

public void populate(String s) {
  myData.setStr1(str1Finder.findStringData(s));
  myData.setBool1(bool1Finder.findBooleanData(s);
}

这个接口(interface)的实现要么定义了一个findStringData,要么定义了一个findBooleanData,这是非常不令人满意的。 populate 方法需要知道我们是否期望使用 findStringData 方法或 findBooleanData 方法。

有更好的方法吗?我是否过于挑剔,因为 populate 方法需要知道 DataFinderInterface 的哪个实例要分配给哪个字段?

最佳答案

返回一个String的单个findData方法应该足够了:处理Booleans的代码可以调用Boolean.getBoolean()在它上面:

public interface DataFinderInterface {
    public String findData(final String input);
}
...
myData.setBool1(Boolean.getBoolean(bool1Finder.findData(s));

关于java - 提取 boolean 值或字符串的接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18276544/

相关文章:

java - Websphere MQ 异步放置不起作用

java - 创建具有多个子元素的 XML 文件

上下文图的 UML 替换

c# - Entity Framework 适合大量实体吗?

nginx - 事件驱动程序nginx如何仅用2个工作进程处理高并发请求?

java - hibernate导入import.sql失败

java - java中获取父目录的父目录名

Python断言语句和代码可重用性

data-structures - 您将如何设计 MAC 地址表(本质上是快速查找表)?

java - 从主类传递参数