有子类中的空方法的解决方案吗? [英] Is there a solution to empty methods in subclass?

查看:179
本文介绍了有子类中的空方法的解决方案吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个超类,有2个子类.如果条件foo为true,则我希望其中一个子类采取某些措施,而其他子类则不执行任何操作:

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.
}

我想出的解决方案:

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?

推荐答案

您所描述的名称有一个名称:它是

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.

如果要避免在子类中编写空的doSomething()方法,那么一种解决方法是将空的doSomething()方法放在超类上.这可以服务于多个子类(假设您总共要担心两个以上的子类),但是就我个人而言,我倾向于对此有些皱眉.覆盖非抽象方法应该是(最好)罕见的例外,而不是常见的做法.

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.

这篇关于有子类中的空方法的解决方案吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆