【问题标题】:Android - Generics and inheritance for todolistsAndroid - todolists 的泛型和继承
【发布时间】:2017-09-05 09:45:36
【问题描述】:

我正在制作一个 Todolist 应用程序。可以创建两种类型的 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;
    }
}

然后我也有“todo”类,但我并不真正需要如何创建它们才能使用“element”的方法,但在 Todolist 的情况下也可以使用“elementImage”的方法“元素图像”...

基本上,“待办事项”类将包含一个名称和一个“元素”列表,但我不知道制作它们的最佳方法是为了减少重复代码而不是破坏实体。

  • 对“todo”使用抽象类?
  • 修改我的“元素”类?
  • 使用泛型?
  • 还有别的吗?

【问题讨论】:

    标签: java android list generics inheritance


    【解决方案1】:

    这似乎是一个不错的开始方式,但是如果你有更多的要求,你可能需要做更多的事情

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

    【讨论】:

    • 是的,这可能是个好主意,因为将来我可能会添加更多类型的列表,例如音频等...但是使用此解决方案我怎么知道这是什么类型的列表?因为我需要这些信息来查看视图...
    • 例如,如果你做 Todo todo = new Todo(new Element);那么你知道这个列表是一个 List,如果我的问题是正确的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    • 2011-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多