Is This Use of the “instanceof” Operator Considered Bad Design?

后端 未结 6 548
南方客
南方客 2020-11-30 04:11

In one of my projects, I have two \"data transfer objects\" RecordType1 and RecordType2 that inherit from an abstract class of RecordType.

I want both RecordType obj

6条回答
  •  生来不讨喜
    2020-11-30 04:31

    Another possible approach would be to make process() (or perhaps call it "doSubclassProcess()" if that clarifies things) abstract (in RecordType), and have the actual implementations in the subclasses. e.g.

    class RecordType {
       protected abstract RecordType doSubclassProcess(RecordType rt);
    
       public process(RecordType rt) {
         // you can do any prelim or common processing here
         // ...
    
         // now do subclass specific stuff...
         return doSubclassProcess(rt);
       }
    }
    
    class RecordType1 extends RecordType {
       protected RecordType1 doSubclassProcess(RecordType RT) {
          // need a cast, but you are pretty sure it is safe here
          RecordType1 rt1 = (RecordType1) rt;
          // now do what you want to rt
          return rt1;
       }
    }
    

    Watch out for a couple of typos - think I fixed them all.

提交回复
热议问题