扩展模型的良好实践?

时间:2014-03-26 17:57:23

标签: java android performance model extend

我在列表视图中使用以下模型:

public class ListItem {
    private int _Id;
    private String Name;


    public ListItem() {
        this._Id = 0;
        this.Name = "";
    }

    public ListItem(int Id, String Name) {
        this._Id = Id;
        this.Name = Name;
    }
        public int getId() {
        return this._Id;
    }

    public void setId(int c) {
        this._Id = c;
    }

    public String getName() {
        return this.Name;
    }

    public void setName(String c) {
        this.Name = c;
    }
}

我有一些额外的数据,一旦他们点击他们想要查看的项目就会显示。由于我从数据库中提取此信息并且我不限制它们放入数据库的项目数量,我想知道是否可以在另一个模型中扩展我的模型。有点像(你可以纠正我,如果这是编写扩展模型的错误方法,如果扩展模型不是一个大问题):

public class ItemDetails extends ListItem {
    private String itemType, Manufacturer, Qty, Notes;
    public ItemDetails () {
        this._Id = 0;
        this.Name = "";
        this.itemType = "";
        this.Manufacturer = "";
        this.Qty = "";
        this.Notes = "";
    }
    public Ammo(int _Id, String name, String itemType,
            String manufacturer, String qty, String notes) {
        this._Id = _Id;
        this.Name = name;
        this.itemType = itemType;
        this.Manufacturer = manufacturer;
        this.Qty = qty;
        this.Notes = notes;
    }

    // Get Variables //
    public int get_Id() {
        return this._Id;
    }

    public String getName() {
        return this.Name;
    }

    public String getItemType() {
        return itemType;
    }

    public String getManufacturer() {
        return Manufacturer;
    }

    public String getQty() {
        return Qty;
    }

    public String getNotes() {
        return Notes;
    }

    // Set Variables //
    public void set_Id(int c) {
        this._Id(c);
    }

    public void setName(int c) {
        this.Name = c;
    }

    public void setItemType(String c) {
        itemType = c;
    }

    public void setManufacturer(String c) {
        Manufacturer = c;
    }

    public void setQty(String c) {
        Qty = c;
    }

    public void setNotes(String c) {
        Notes = c;
    }

}

这会是一个坏主意吗?我是不是只需要不同的模型或一个模型,只返回我需要的数据从List然后获取其余的数据?我正在尝试用这个编写干净的代码,并尽可能少地重复代码。我也希望我的代码有效并且表现良好,但我不确定这是否是一个好主意。

2 个答案:

答案 0 :(得分:1)

看起来你没有使用你正在扩展的类中的大部分代码(变量和方法)。如果在创建ItemDetails的对象(如ListItem item = new ItemDetails();)时没有明确需要获取ListItem的对象,则实际上没有理由扩展该类。在这种情况下,如果你不进行扩展,你的代码肯定更干净。

答案 1 :(得分:0)

如果你想编写干净的代码,你应该明白构造函数调用ListItem构造函数并且已经初始化字段“_Id”和“Name”,并且不建议重写方法而不需要更改它们。