2015-12-10 363 views
0

我試圖將一個數據集(我們稱之爲Set1)映射到另一個(Set2)上。通過對Set1的子集應用操作並將結果放置到Set2的對象來完成映射。我想知道如何以高效和優雅的方式構造類(試圖學習OOP)。下面的代碼正在工作,但類的初始化順序和內容有些尷尬。將一組對象映射到另一個對象

interface Operator{ 
    public void transform(List<String> from, Element to); 
} 
class Transform{ 
    public List<String> fromIndex; 
    public Integer toIndex; 
    Operator op; 
    Mapper m;//NICE TO NOT HAVE ref to Mapper 
    Transform(List<String> fromIndex, Integer toIndex, Operator op, Mapper m){ 
     this.fromIndex = fromIndex; 
     this.toIndex = toIndex; 
     this.op = op; 
     this.m = m; 
    } 
    public void execute(){ 
     List<String> from = new ArrayList<String>(); 
     Element to = m.Set2.get(toIndex); 
     for(String s : fromIndex){ 
      from.add(m.Set1.get(s)); 
     } 
     op.transform(from,to); 
    } 
} 
class Mapper{ 
    Map<String,String> Set1; 
    Map<Integer,Element> Set2; 
    List<Transform> transforms; 
    Mapper(Map<String,String> Set1, Map<Integer,Element> Set2){ 
     this.Set1= Set1; 
     this.Set2= Set2; 
    } 
    public void setTransforms(List<Transform> transforms){ 
     this.transforms = transforms; 
    } 
    public void doMapping(){ 
     for(Transform t: transforms){ 
      t.execute(); 
     } 
    } 
} 

典型使用場景,假設SET1和SET2已經填滿(SET2充滿元素,其值將被更新):

List<Transform> tList = new ArrayList<Transform>(); 
Mapper m = new Mapper(Set1,Set2); 
tList.add(new Transform(new ArrayList<String>(Arrays.asList("3", "3_")),3,concatStringToInteger,m)); 
tList.add(new Transform(new ArrayList<String>(Arrays.asList("4", "4_")),4,concatStringToInteger,m)); 
tList.add(new Transform(new ArrayList<String>(Arrays.asList("22")),22,concatStringToInteger,m)); 
tList.add(new Transform(new ArrayList<String>(Arrays.asList("24")),24,concatStringToInteger,m)); 
m.setTransforms(tList); 
m.doMapping(); 

的運營商都只是一些可重複使用的蘭巴進出口。正如你所看到的,Transform需要持有映射器的引用,並且整個初始化非常尷尬。這不是一個關於功能的問題(所以請忽略任何代碼錯誤,代碼工作),而是關於在OOP(並保持一定程度的通用性)中構造這個問題。 謝謝

+4

我投票是題外話,因爲它屬於在關閉這個問題[代碼審查] (https://codereview.stackexchange.com/)。 –

回答

0

你有一個操作,它接受一個字符串列表並映射到一個Element類型的對象。以編程方式,這意味着Element類型的對象可以從字符串列表構造。現在

,從類型元素開始:

class Element { 
     some attributes 

     // some default constructor 

    // constructor needed for this case, 
    Element(List<String> from); 
} 

程序的其餘

class Mapper{ 
    Some Collection of input I 
    Element e; 
    Some Collection of ouput O 

    ... 
    within a loop 
     // construct a single element 
     e = Element(get input from I) 
     // add new element to output collection 
     O.add(e) 

} 
相關問題