2013-10-28 180 views
0

大家下午好。在java中封装对象

我在想Java中的一些问题。我工作到现在的所有公司从来不会打扰自己的良好和封装代码。因为我在我自己的脑海中提出了这个问题。

有什么更好的,微妙的方式来解决一些对象的老问题。

使用getter和setter(不验证)创建anemics实体,或将相同的对象作为参数和它们的属性的新值随后传递。

例:

anemics实体:

public class RenterGrouping implements Serializable { 

    private Integer idRenterGrouping; 
    private String name; 
public RenterGrouping() { 
} 

public RenterGrouping(String name) { 
    this.name = name; 
} 


@Id 
@GeneratedValue(strategy = GenerationType.IDENTITY) 
@Column(name = "idRenterGrouping", unique = true, nullable = false) 
public Integer getIdRenterGrouping() { 
    return idRenterGrouping; 
} 


@Column(name = "name") 
public String getName() { 
    return name; 
} 


public void setIdRenterGrouping(Integer idRenterGrouping) { 
    this.idRenterGrouping = idRenterGrouping; 
} 


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

}

或替代的第二种方式(不制定者):

public class RenterGrouping implements Serializable { 

private Integer idRenterGrouping; 
private String name; 

public RenterGrouping() { 
} 

public RenterGrouping(String name) { 
    this.name = name; 
} 


public RenterGrouping updateRenterGrouping(RenterGrouping renterGrouping, Integer idRenterGrouping, String name) { 
    renterGrouping.idRenterGrouping = idRenterGrouping != null? idRenterGrouping : null; 
    renterGrouping.name = name != null? name : null; 

    return renterGrouping; 

} 


@Id 
@GeneratedValue(strategy = GenerationType.IDENTITY) 
@Column(name = "idRenterGrouping", unique = true, nullable = false) 
public Integer getIdRenterGrouping() { 
    return idRenterGrouping; 
} 


@Column(name = "name") 
public String getName() { 
    return name; 
} 

这里的进口实际上是保护对象和他们的属性。

其他人与方法updateRenterGrouping

等待你的反馈球员。 谢谢你们!

+1

所以你想要一个可能有几十个参数的方法,它们不会更新对象中的任何值,部分或全部值?不会通过我的代码审查。 – Kayaman

+1

是否不需要有条件的操作符? – MrBackend

+0

我的字典中不存在贫血症(除了可能指的是贫血症,由于血液或血细胞缺乏导致的疾病...)。请澄清与Java类有关的术语。 – tucuxi

回答

0

看就是调用实体的方法:

public RenterGroupingTO saveOrUpdate(Integer idRenterGrouping, String name) throws Throwable { 

    RenterGrouping renterGrouping; 

    if (idRenterGrouping != null && idRenterGrouping != 0) { 
     renterGrouping = getById(idRenterGrouping); 
     renterGrouping = renterGrouping.updateRenterGrouping(renterGrouping, idRenterGrouping, name); // calls the method 

    } else { 

     renterGrouping = new RenterGrouping(name); 
    } 

    FactoryDAO.getInstance().getRenterGroupingDAO().saveOrUpdate(renterGrouping); 
    return new RenterGroupingTO(renterGrouping); 
} 

它持之以恒自己做这样的事情:

renterGrouping = getById(idRenterGrouping); 
renterGrouping.setIdRenterGrouping(idRenterGrouping); 
renterGrouping.setName(name); 

Kayaman 假设我们有10个参数,同样这种方式,我们只需要调用updateRenterGrouping(parameters ...)方法,而不是在每个我们想要在这些属性中输入值的地方创建10个setter,并将其更改为实体。 另一种可能性是:相反,为每个属性创建entity.setAtribute(x),我们有为我们做的方法。

不值得吗?

+0

如果你想节省代码,你可以通过反省来节省成本;但是,您将失去编译时的完整性检查。在使用内省来设置字段之前,我会建议将这些字段公开并调用一个“persist()”方法。另一方面,大多数IDE可以自动生成getter/setter。是的,它是样板文件;但它不是/那么昂贵。 – tucuxi