在java中,我正在编写一些DTO对象,这些对象都继承自AllocationDTO
然后将这些对象的列表传递到DAO对象以保存到数据库。
根据保存AllocationDTO
的哪个子类型,保存逻辑会更改(例如,数据库中要保存的表格等)
我发现自己使用代码:
for (AllocationDTO x : listOfAllocationDtos) {
if (x instanceof ManagerAllocationDTO) {
Manager m = (x(ManagerAllocationDTO)).getManager();
// save manager etc to managerallocs
} else if (x.getId() == AllocationDTO.TYPE_SPECIAL1) {
// save to specialAlloc1 table
} else if (x.getId() == AllocationDTO.TYPE_SPECIAL2) {
// save to specialAlloc2 table
}
}
ManagerAllocationDTO
有一个额外的字段,将分配与管理器相关联,但对于specialalloc1 / 2,我没有创建子类型,因为数据的唯一区别是它保存到的表。
我的问题是一个软设计问题 - 这是最好的方法吗?
答案 0 :(得分:1)
在没有instanceOf
和if-else-cascade的情况下分离不同实例的一种方法是使用Visitor Design pattern。
新接口:AllocationVisitor,为AllocationDTO的每个具体子类提供一个方法:
AllocationDTO:abstract void acceptVisitor(AllocationVisitor visitor)
void acceptVisitor(AllocationVisitor visitor){visit(this);}
//正确的访问方法由编译时类型选择。DAO:
AllocationVisitor saveVisitor = new AllocationVisitor() {
visit(TYPE_SPCIAL1 dto) {//what ever you need}
visit(TYPE_SPCIAL2 dto) {//what ever TYPE_SPCIAL2 needs}
}
for (AllocationDTO x : listOfAllocationDtos) {
x.visit(saveVisitor);
}