2017-04-10 89 views
0

我正在製作Todolist應用程序。有兩種類型的todolist可以創建。第一個是經典的,只是一串字符串。第二個是圖像集合(每個圖像也有一個字符串來描述它)。Android - Todolist的泛型和繼承

所以我的課是:

public class Element { 
    private String text; 

    public Element(String text){ 
     this.text = text; 
    } 

    public void editText(String text){ 
     this.text = text; 
    } 
} 

元素圖像

public class ElementImage extends Element { 
    private Image image; 

    public ElementImage(String text, Image image){ 
     super(text); 
     this.image = image; 
    } 

    public void editImage(Image image){ 
     this.image = image; 
    } 
} 

然後我也有「待辦事項」類,但我真的不我需要如何創建他們能夠使用「元素」的方法,而且在「元素圖像」的Todolist的情況下也可以使用「元素圖像」的方法...

基本上「待辦事項」類將包含一個名稱和一個「元素」列表,但我不知道什麼是最好的方式來使他們爲了有較少重複的代碼,而不是堅實。

  • 對「todo」使用抽象類?
  • 修改我的「元素」類?
  • 使用泛型?
  • 還有別的嗎?

回答

0

這似乎是一個良好的開端,但你可能需要做更多,如果你有更多的需求

public class Todo<T>{ // T can represent Element or ElementImage or anything you want. 
    T element; 
    private List<T> list = new ArrayList<>(); 
    public Todo(T element){ 
     this.element = element; 
    } 

    T getElemet(){ 
     return element; // If T is ElementImage or just Element you can get it and do what you want 

    } 
    // Now you would need to add further logic and more stuff. 
    public List<T> getTodoList(){ return list;} 
} 
+0

是啊,這可能是一個好主意,因爲在將來,我可能會添加更多的類型的列表,如音頻等......但有了這個解決方案,我怎麼能知道這是什麼類型的列表?因爲我需要這些信息... – MBek

+0

例如,如果你做Todo todo = new Todo(new Element);然後你知道這個清單是列表,如果我有你的問題。 –

+0

噢對了:)謝謝! – MBek