在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有一个额外的字段,将分配与管理器联系起来,但对于特殊的alloc1/2情况,我没有创建子类型,因为数据中唯一的区别是它保存到的表。
我的问题有点软设计问题--这是做这件事的最佳方式吗?
发布于 2011-05-19 19:45:00
分离不同实例的一种方法是使用Visitor Design pattern,而无需instanceOf和if-else-cascade。
的每个具体子类使用一个方法的AllocationVisitor
- visit(TYPE\_SPCIAL1 dto)
- visit(TYPE\_SPCIAL2 dto)
acceptVisitor(AllocationVisitor访问者)
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);
}https://stackoverflow.com/questions/6058063
复制相似问题