2013-08-16 65 views
0

所以我有一個有點奠定了作爲一個數據類:接口提取一個布爾值或字符串

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實際上是一些漂亮的毛茸茸的條件,所以不是我定義的接口:

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); 
} 

這個接口的任一定義findStringData或findBooleanData,這是相當不令人滿意的實現。填充方法需要知道我們是否期望使用findStringData方法或findBooleanData方法。

有沒有更好的方法來做到這一點?我是過於挑剔,因爲填充方法需要知道什麼樣的DataFinderInterface實例分配到哪個字段呢?

+2

我不知道這是否只有我,但你的問題不是很清楚。這看起來像[XY問題](http://meta.stackexchange.com/q/66377/196975)。可能你應該先解釋你的問題陳述。你想要做什麼,然後你現在擁有什麼。 –

+0

填充也需要能夠設置'str2','str3'和'bool2'? –

回答

1

findData方法返回一個String應該是足夠的:即處理Booleans代碼可以把呼叫Boolean.getBoolean()在它的上面:

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

考慮使用正則表達式從輸入字符串中提取所需的數據。我將MyData類作爲一個簡單的數據容器,並構建一個單獨的類來填充它 - 例如MyDataBuilder。該類可以使用字符串匹配來提取字段並將其填充到對象上。

1

上述問題(或其中一個問題)是您總是打電話給setStr1setBool1,我假設您也會打電話給所有其他人。

如果您必須使用上述模式,您可能需要考慮讓MyData保持AtomicRefernce<String>AtomicReference<Boolean>。然後有getSettableStringgetSettableBoolean方法返回適當的引用,如果不匹配則返回null。

0

如果只是接口方法簽名你擔心這可以使用泛型來解決。然而,以這種方式從字符串初始化對象似乎有點奇怪。也許如果你添加更多關於你想要解決什麼問題的細節,可能會有更好的解決方案。

public interface DataFinder<T> { 
    public T findData(final String input); 
} 

DataFinder<String> str1Finder = new ... // a class implementing DataFinder<String> 
DataFinder<Boolean> bool1Finder = new ... // a class implementing DataFinder<Boolean> 

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