Is there a solution to empty methods in subclass?

2019-09-15 02:11发布

问题:

I have a super class, with 2 subclasses. If condition foo is true I want one of the subclass to take some action while other subclass should do nothing:

public void doFoo() {
   // some 10 lines common to both subclasses.
   boolean foo = checkFoo();

   /**
    *  if foo is true, subclass1 should do something. subcass2 does nothing.
    */ 

   // some 10 lines common to both subclasses.
}

The solution I came up with:

public void doFoo() {
   // some 10 lines common to both subclasses.
   boolean foo = checkFoo();

   if (foo) {
      doSomething();
   } 

   // some 10 lines common to both subclasses.
}

class subclass1 extends superclass {
   public void doSomething()  {
     // some lines of code.
   }

}

class subclass2 extends superclass {
   public void doSomething()  {
     // do nothing
   }
}

Any cleaner, better, more standard solution to this common problem?

回答1:

What you are describing has a name: it is the Template Method pattern. Design patterns aren't so hyped these days as once they were, but the Template Method pattern is still a tried and true approach to the general sort of problem you describe.

If you want to avoid writing empty doSomething() methods in subclasses, then one way to go about it would be to put an empty doSomething() method on the superclass instead. That can serve multiple subclasses (supposing that you have more than two overall to worry about), but personally, I'm inclined to frown on that a bit. Overriding non-abstract methods ought to be the rare (at best) exception, not a common practice.



回答2:

That is the "correct" approach. But some notes:

  • doSomething() could be abstract (if you want to enforce that each subclass has to provide a specific implementation)
  • doFoo() on the other hand should be final in order to prevent subclasses from changing that behavior.