简体   繁体   English

默认实现还是抽象方法?

[英]Default implementation or abstract method?

Is it better to put a default implementation of a method in a superclass, and override it when subclasses want to deviate from this, or should you just leave the superclass method abstract, and have the normal implementation repeated across many subclasses? 将方法的默认实现放在超类中更好,并在子类想要偏离它时重写它,或者你应该只留下超类方法摘要,并在许多子类中重复正常实现?

For example, a project I am involved in has a class that is used to specify the conditions in which it should halt. 例如,我参与的项目有一个类,用于指定它应该停止的条件。 The abstract class is as follows: 抽象类如下:

public abstract class HaltingCondition{
    public abstract boolean isFinished(State s);
}

A trivial implementation might be: 一个简单的实现可能是:

public class AlwaysHaltingCondition extends HaltingCondition{
    public boolean isFinished(State s){
        return true;
    }
}

The reason we do this with objects is that we can then arbitrarily compose these objects together. 我们用对象做这个的原因是我们可以随意组合这些对象。 For instance: 例如:

public class ConjunctionHaltingCondition extends HaltingCondition{
    private Set<HaltingCondition> conditions;

    public void isFinished(State s){
        boolean finished = true;
        Iterator<HaltingCondition> it = conditions.iterator();
        while(it.hasNext()){
            finished = finished && it.next().isFinished(s);
        }
        return finished;
    }
}

However, we have some halting conditions that need to be notified that events have occurred. 但是,我们有一些暂停条件需要通知事件已经发生。 For instance: 例如:

public class HaltAfterAnyEventHaltingCondition extends HaltingCondition{
    private boolean eventHasOccurred = false;

    public void eventHasOccurred(Event e){
        eventHasOccurred = true;
    }

    public boolean isFinished(State s){
        return eventHasOccurred;
    }
}

How should we best represent eventHasOccurred(Event e) in the abstract superclass? 我们应该如何在抽象超类中最好地表示eventHasOccurred(Event e) Most subclasses can have a no-op implementation of this method (eg AlwaysHaltingCondition ), while some require a significant implementation to operate correctly (eg HaltAfterAnyEventHaltingCondition ) and others do not need to do anything with the message, but must pass it on to their subordinates so that they will operate correctly (eg ConjunctionHaltingCondition ). 大多数子类可以具有此方法的无操作实现(例如, AlwaysHaltingCondition ),而有些子类需要重要的实现才能正常运行(例如HaltAfterAnyEventHaltingCondition ),而其他子类不需要对消息执行任何操作,但必须将其传递给其下属这样它们才能正常运行(例如ConjunctionHaltingCondition )。

We could have a default implementation, which would reduce code duplication, but would cause some subclasses to compile yet not operate correctly if it wasn't overridden, or we could have the method declared as abstract, which would require the author of every subclass to think about the implementation they were providing, although nine times out of ten it would be a no-op implementation. 我们可以有一个默认实现,它可以减少代码重复,但会导致一些子类编译但如果没有被覆盖则不能正常运行,或者我们可以将方法声明为abstract,这将需要每个子类的作者考虑一下它们提供的实现,尽管十分之九是无操作实现。 What are the other pros and cons of these strategies? 这些策略的其他优缺点是什么? Is one much better than the other? 一个比另一个好多少?

One option is to have another abstract subclass, to use as the superclass for all implementations which do want to use the default implementation. 一种选择是有另一个抽象类,作为超对于这确实想使用的默认实现全部实现使用。

Personally I usually leave non-final methods abstract in an abstract class (or just use interfaces instead) but it definitely depends on the situation. 就个人而言,我通常将抽象类中的非最终方法抽象(或者仅使用接口),但它肯定取决于具体情况。 If you have an interface with many methods, and you want to be able to just opt in to some of them, for example, then an abstract class which implements the interface in a no-op way for every method is fine. 例如,如果你有一个包含许多方法的接口,并且你希望能够选择加入其中一些方法,那么一个抽象类就可以为每个方法以无操作的方式实现接口。

You need to evaluate each case on its merits, basically. 基本上,你需要根据其优点来评估每个案例。

It sounds like you are concerned about setting that boolean variable when the event happens. 听起来你担心在事件发生时设置该布尔变量。 If the user overrides eventHasOccurred() , then the boolean variable will not be set and isFinished() will not return the correct value. 如果用户重写eventHasOccurred() ,则不会设置布尔变量,并且isFinished()将不返回正确的值。 To do this, you can have one abstract method which the user overrides to handle the event and another method which calls the abstract method and sets the boolean value (see the code sample below). 为此,您可以使用一个用户覆盖的抽象方法来处理事件,另一个方法调用抽象方法并设置布尔值(请参阅下面的代码示例)。

Also, instead of putting the eventHasOccurred() method in the HaltingCondition class, you can just have the classes that need to handle events extend a class which defines this method (like the class below). 此外,不是将eventHasOccurred()方法放在HaltingCondition类中,您可以让需要处理事件的类扩展一个定义此方法的类(如下面的类)。 Any class that does not need to handle events can just extend HaltingCondition : 任何不需要处理事件的类都可以扩展HaltingCondition

public abstract class EventHaltingCondition extends HaltingCondition{
  private boolean eventHasOccurred = false;

  //child class implements this
  //notice how it has protected access to ensure that the public eventHasOccurred() method is called
  protected abstract void handleEvent(Event e);

  //program calls this when the event happens
  public final void eventHasOccurred(Event e){
    eventHasOccurred = true; //boolean is set so that isFinished() returns the proper value
    handleEvent(e); //child class' custom code is executed
  }

  @Override
  public boolean isFinished(){
    return eventHasOcccurred;
  }
}

EDIT (see comments): 编辑(见评论):

final EventHaltingCondition condition = new EventHaltingCondition(){
  @Override
  protected void handleEvent(Event e){
    //...
  }
};
JButton button = new JButton("click me");
button.addActionListener(new ActionListener(){
  public void actionPerformed(ActionEvent actionEvent){
    //runs when the button is clicked

    Event event = //...
    condition.eventHasOccurred(event);
  }
});

If you are going to put any implementation in the abstract base class, it should be the code for the sub-classes that use the no-op implementation, since this is an implementation that makes sense for the base class as well. 如果要将任何实现放在抽象基类中,它应该是使用no-op实现的子类的代码,因为这是一个对基类也有意义的实现。 If there were no sensible implementation for the base class (eg, if there was no sensible no-op for the method you're discussing here), then I'd suggest leaving it abstract. 如果基类没有合理的实现(例如,如果你在这里讨论的方法没有明智的无操作),那么我建议将它留作抽象。

With respect to duplicated code, if there are "families" of classes that all use the same implementation of the method and you don't want to duplicate the code across all classes in the family, you might simply use helper classes per family that supply these implementations. 对于重复的代码,如果存在所有使用相同方法实现的类的“族”,并且您不希望在该族中的所有类中复制代码,则可以简单地使用每个族的帮助程序类。这些实现。 In your example, a helper for classes that pass down the events, a helper for classes accept and record the event, etc. 在您的示例中,传递事件的类的助手,类的助手接受并记录事件等。

I encountered a similar scenario when I created the basic outline (class hierarchy) of an application I was developing together with others at work. 当我创建与工作中的其他人一起开发的应用程序的基本大纲(类层次结构)时,我遇到了类似的情况。 My choice for placing a method abstract (and consequently to force its implementation) was for communication purposes. 我选择放置方法摘要 (并因此强制其实现)是出于通信目的。

Basically the other team mates had somehow to explicitly implement the method and therefore first of all notice its presence and second agree on what they return there, even if it is just the default implementation. 基本上,其他队友已经以某种方式明确地实现了该方法,因此首先注意到它的存在,并且第二个同意他们返回那里,即使它只是默认实现。

Default implementations in base classes often get overlooked. 基类中的默认实现经常被忽略。

If you are leaving the super class method abstract you may want to look into utilizing an Interface (not to be confused with an interface). 如果您要离开超类方法摘要,您可能需要考虑使用接口(不要与接口混淆)。 As the Interface is one that does not provide a concrete implementation. 因为接口是不提供具体实现的接口。

Scott 斯科特

To expand, when we as programmers are instructed to code to an interface often times new, and sometimes experienced, developers will assume incorrectly that it is in reference to the keyword Interface wherein no implementation details may be found. 为了扩展,当我们作为程序员被指示经常对新的,有时经验丰富的接口进行编码时,开发人员会错误地认为它是在引用关键字接口,其中没有找到实现细节。 However, the more clear way of saying this is that any top level object can be treated as an interface which can be interacted with. 然而,更明确的说法是任何顶级对象都可以被视为可以与之交互的界面。 For instance an abstract class called Animal would be an interface would a class called Cat that would inherit from Animal. 例如,名为Animal的抽象类将是一个名为Cat的类,它将继承自Animal。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM