从具有指定属性的域对象中的集合中检索对象的最佳做法是什么?
例如,我们有一个汽车保险应用程序,它有两个类:一个有汽车列表的人。如果我总是需要从具有指定 VIN 的人处检索汽车,那么实现该方法的最佳方式是什么?我在下面提供了一些示例 - 欢迎其他示例
示例 1
在 Person 实体中添加一个新方法来检索 VIN
public class Person
{
private HashSet<Car> cars = new HashSet<Car>();
public Set<Car> getCars()
{
return this.cars;
}
public Car getCarByVin(VIN vin)
{
//loop over cars and retrieve the car with the VIN
}
}
So from an application the process would be...
VIN vin = new VIN(...);
Person person = personDao.getPerson();
Car personCar = person.getCarByVin(vin);
示例 2
在 Person 实体中创建一个新的列表集合,并将通过 VIN 方法检索添加到集合中
public class Person
{
private CarSet cars = new CarSet();
public CarSet getCars()
{
return this.cars;
}
}
public class CarSet
implements Set<Car>
{
//implement required methods for Set
public Car byVin(VIN vin)
{
//loop over set and retrieve the car with the VIN
}
}
So from an application the process would be...
VIN vin = new VIN(...);
Person person = personDao.getPerson();
Car personCar = person.getCars().byVin(vin);
最佳答案
我认为 Demeter 法则适用于第一个示例。任何时候链接,例如 foo.getBar().doBlah(),都会违反 Demeter 法则。这显然不是一条法律,但它是一个很好的指导方针,适用于当一个类必须了解关于另一个类中的位的太多细节时。
关于java - 从域模型中检索集合中的项目的最佳做法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1364479/