开发者

instanceof vs isAnX()

In java i am writing some DTO objects, which all inherit from AllocationDTO.

A list of these objects are then passed into a DAO object for saving to the database.

Depending on which subtype of AllocationDTO is being saved the saving logic changes (e.g. which table in the database to save to etc.)

I find myself using code as such:

for (AllocationDTO x 开发者_JS百科: 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
    }
}

The ManagerAllocationDTO has an extra field relating the allocation to a manager, but for the specialalloc1/2 cases I have not made a subtype because the only difference in the data is the table it is saved to.

My question is a bit of a soft design question - is this the best way to go about doing this?


One way to seperate different instances, without instanceOf and if-else-cascade is to use the Visitor Design pattern.

  • new Interface: AllocationVisitor with one method for each concrete subclass of AllocationDTO:

    • visit(TYPE_SPCIAL1 dto)
    • visit(TYPE_SPCIAL2 dto)
  • AllocationDTO: abstract void acceptVisitor(AllocationVisitor visitor)

  • Each concreate subclass of AllocationDTO implements the acceptVisitor() this way: void acceptVisitor(AllocationVisitor visitor){visit(this);} //the correct visit method is choosen by compile time type.
  • Your DTO implements the AllocationVisitor Interface (with an inner class), create an instance of this, and passes it to the elements of listOfAllocationDtos.

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);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜