2017-04-10 90 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