《On Java 中文版 基础卷》阅读笔记 接口 18

《On Java 中文版 基础卷》阅读笔记 接口 18

"接口和抽象类提供了一种更加结构化的方式来分离接口与实现。​"

接口和抽象类在编程语言中并不常见,例如,C++ 仅间接支持这些概念。

Java 中存在的对应关键字表明,其设计者认为这些思想足够重要,值得提供对它们的直接支持。

首先,我们将介绍抽象类 (abstract class),它介于普通类和接口之间。

尽管你的第一反应是创建接口,但在构建具有字段和未实现方法的类时,抽象类是重要且必需的工具。你不能总是使用纯接口。

10.1 抽象类和抽象方法

在上一章的所有 "乐器" 示例中,基类 Instrument 中的方法都是 "哑" (dummy) 方法。

调用这些方法是不明智的,因为 Instrument 的目的是为它的子类创建一个公共接口。

在这些示例中,创建此通用接口的唯一原因是,不同的子类型可以用不同的方式来表示这个接口。

它建立了一种基本形式,这样你就可以抽象出所有子类的共同之处。

换言之,Instrument 可称为抽象基类,或简称为抽象类。

对于像 Instrument 这样的抽象类,其对象几乎总是没有意义的。

我们创建抽象类,是想通过一个公共接口来操作一组类。

因此 Instrument 仅表示接口,而不是特定的实现,仅创建一个 Instrument 对象并没有什么意义,所以你可能想阻止用户这样做。

我们可以让 Instrument 中的所有方法都产生错误 ,但这样做会拖延到运行时才报错,并且需要用户进行可靠的详尽测试。

通常最好在编译时就能发现这些问题。

为此,Java 提供了一种称为抽象方法 (abstract method) 的机制。

这是一个不完整的方法,它只有一个声明,没有方法体。以下是抽象方法声明的语法:

java 复制代码
abstract void f();

包含抽象方法的类称为抽象类。

如果一个类包含一个或多个抽象方法,则该类必须被定义为抽象类,否则编译器会产生错误消息。

java 复制代码
package interfaces;
// interfaces/Basic.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.

abstract class Basic {
  abstract void unimplemented();
}

如果抽象类不完整,那么当试图创建该类的对象时会发生什么?

答案是你无法安全地创建抽象类的对象,因此会收到来自编译器的错误消息。

这样就保证了抽象类的纯粹,不用担心它会被误用。

java 复制代码
package interfaces;
// interfaces/AttemptToUseBasic.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// {WillNotCompile}

public class AttemptToUseBasic {
  Basic b = new Basic();
  // error: Basic is abstract; cannot be instantiated
}

如果一个新类型继承了抽象类,并希望能生成自己的对象,那它必须为基类中的所有抽象方法提供方法定义。

如果不这样做(你可能会选择不这样做)​,那么子类也是抽象的,编译器将强制你使用 abstract 关键字来限定这个子类。

java 复制代码
package interfaces;
// interfaces/Basic2.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.

abstract class Basic2 extends Basic {
  int f() { return 111; }
  abstract void g();
  // unimplemented() still not implemented
}

一个抽象类可以不包含任何抽象方法。
如果一个类并不需要包含抽象方法,但同时还想阻止对它的任何实例化,
这时将其定义为抽象类就很有用了。

java 复制代码
package interfaces;
// interfaces/AbstractWithoutAbstracts.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.

abstract class Basic3 {
  int f() { return 111; }
  // No abstract methods
}

public class AbstractWithoutAbstracts {
  // Basic3 b3 = new Basic3();
  // error: Basic3 is abstract; cannot be instantiated
}

要想创建一个可实例化的类,继承抽象类后需要为所有的抽象方法提供定义:

java 复制代码
package interfaces;
// interfaces/Instantiable.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.

abstract class Uninstantiable {
  abstract void f();
  abstract int g();
}

public class Instantiable extends Uninstantiable {
  @Override 
  void f() { System.out.println("f()"); }
  @Override 
  int g() { return 22; }
  public static void main(String[] args) {
    Uninstantiable ui = new Instantiable();
  }
}

注意 @Override 的使用。

即使没有这个注解,只要没有使用相同的方法名称或方法签名,抽象机制仍能发现你没有实现抽象方法,并产生一个编译时错误。

因此,你可以有理有据地争辩说,@Override 在这里是多余的。

但 @Override 可以给读者提示,表明这个方法是被重写了的------我认为这很有用,

所以即使编译器会在没有它的情况下也提示错误,我还是会使用 @Override。

请记住,默认的访问权限是 "友好的"​( friendly,即包访问权限)​。

你很快就会了解到,接口自动将其方法设为了 public。

事实上,接口里只允许有 public 方法,如果不提供访问权限修饰符,它的方法默认不是 "友好的"​,而是 public 的。
抽象类则几乎对访问权限没有什么限制:

java 复制代码
package interfaces;
// interfaces/AbstractAccess.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.

abstract class AbstractAccess {
  private void m1() {}
  // private abstract void m1a(); // illegal
  protected void m2() {}
  protected abstract void m2a();
  void m3() {}
  abstract void m3a();
  public void m4() {}
  public abstract void m4a();
}

不允许使用 private abstract 是有道理的,因为在 AbstractAccess 的任何子类中都不可能给这样的方法提供一个合法的定义。

上一章的 Instrument 类可以很容易地改成一个抽象类。

抽象类并不会强制要求其所有方法都是抽象的,因此只需要将部分方法声明为 abstract 就可以了,如图 10-1 所示。

图 10-1

下面是改用抽象类和方法实现的管弦乐队示例:

java 复制代码
// interfaces/music4/Music4.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// Abstract classes and methods
// {java interfaces.music4.Music4}
package interfaces.music4;
import polymorphism.music.Note;

abstract class Instrument {
  private int i; // Storage allocated for each
  public abstract void play(Note n);
  public String what() { return "Instrument"; }
  public abstract void adjust();
}

class Wind extends Instrument {
  @Override public void play(Note n) {
    System.out.println("Wind.play() " + n);
  }
  @Override public String what() { return "Wind"; }
  @Override public void adjust() {
    System.out.println("Adjusting Wind");
  }
}

class Percussion extends Instrument {
  @Override public void play(Note n) {
    System.out.println("Percussion.play() " + n);
  }
  @Override public String what() {
    return "Percussion";
  }
  @Override public void adjust() {
    System.out.println("Adjusting Percussion");
  }
}

class Stringed extends Instrument {
  @Override public void play(Note n) {
    System.out.println("Stringed.play() " + n);
  }
  @Override public String what() { return "Stringed"; }
  @Override public void adjust() {
    System.out.println("Adjusting Stringed");
  }
}

class Brass extends Wind {
  @Override public void play(Note n) {
    System.out.println("Brass.play() " + n);
  }
  @Override public void adjust() {
    System.out.println("Adjusting Brass");
  }
}

class Woodwind extends Wind {
  @Override public void play(Note n) {
    System.out.println("Woodwind.play() " + n);
  }
  @Override public String what() { return "Woodwind"; }
}

public class Music4 {
  // Doesn't care about type, so new types
  // added to the system still work right:
  static void tune(Instrument i) {
    // ...
    i.play(Note.MIDDLE_C);
  }
  static void tuneAll(Instrument[] e) {
    for(Instrument i : e)
      tune(i);
  }
  public static void main(String[] args) {
    // Upcasting during addition to the array:
    Instrument[] orchestra = {
      new Wind(),
      new Percussion(),
      new Stringed(),
      new Brass(),
      new Woodwind()
    };
    tuneAll(orchestra);
  }
}
/* Output:
Wind.play() MIDDLE_C
Percussion.play() MIDDLE_C
Stringed.play() MIDDLE_C
Brass.play() MIDDLE_C
Woodwind.play() MIDDLE_C
*/

除了 Instrument,这个示例并没有什么变化。

抽象类和抽象方法很有用,因为它们明确了类的抽象性,并告诉用户和编译器自己的预期用途。

抽象类还是有用的重构工具,它能让你轻松地在继承层次结构中向上移动通用方法。

10.2 接口定义

我们使用关键字 interface 来定义接口。​"接口" 这个词在本书中很常见。就像 "类" 一样。

除非特别提到关键字 interface,否则我会直接用 "接口" 一词指代。

在 Java 8 之前,接口更容易描述,因为它只允许使用抽象方法,看起来是这样的:

java 复制代码
package interfaces;
// interfaces/PureInterface.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// Interface only looked like this before Java 8

public interface PureInterface {
  int m1();
  void m2();
  double m3();
}

这里甚至不需要在方法上使用 abstract 关键字------因为它们在接口中,

Java 知道它们不能有方法体(你仍然可以添加 abstract 关键字,但这只会让人觉得你不懂接口,使自己尴尬)​。

所以,在 Java 8 之前,我们可以这样说:

interface 关键字创建了一个完全抽象的类,它不代表任何实现。

接口描述了一个类应该是什么样子和做什么的,而不是应该如何做。

它确定了方法名、参数列表和返回类型,但不提供方法主体。

接口只提供一种形式,并且除了某些受限制的情况外,它通常不提供实现。

对于一个接口来说,它其实是在表示 "所有实现了这个特定接口的类看起来都像这样"​。

因此,任何使用了特定接口的代码都知道该接口可以调用哪些方法,仅此而已。

所以接口是用来在类之间建立 "协议" 的(一些面向对象编程语言有 protocol 关键字,可以做同样的事情)​。

Java 8 中的接口变得有点混乱,因为 Java 8 允许默认方法和静态方法 ------随着对本书学习的深入,你会理解这么做的原因。

接口的基本概念仍然成立,即它更多的是一个类型的概念,而不是实现。

接口和抽象类之间最显著的区别可能是两者的惯用方式。
接口通常暗示 "类的类型" 或作为形容词来使用,例如 Runnable 或 Serializable,
而抽象类通常是类层次结构的一部分,并且是 "事物的类型"​,例如 String 或 Instrument。

要创建接口,请使用 interface 关键字而不是 class 关键字。

与类一样,你可以在 interface 关键字之前添加 public 关键字(但前提是该接口定义在同名文件中)​。

如果去掉 public 关键字,你将获得包访问权限,这样的话该接口就只能在同一个包内使用。

接口也可以包含字段,但这些字段是隐式的 static 和 final。

要创建一个符合特定接口(或一组接口)的类,请使用 implements 关键字,

它表示 "接口只是定义了它看起来是怎样的,但现在我要声明它是如何工作的"​。

除此之外,它看起来像继承。

java 复制代码
package interfaces;
// interfaces/ImplementingAnInterface.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.

interface Concept { // Package access
  void idea1();
  void idea2();
}

class Implementation implements Concept {
  @Override public void idea1() {
    System.out.println("idea1");
  }
  @Override public void idea2() {
    System.out.println("idea2");
  }
}

你可以选择将接口中的方法显式声明为 public,但即使不显式声明,它们也是 public 的。

所以当实现一个接口时,来自接口的方法必须被定义为 public。

否则,它们将默认为包访问权限,导致在继承期间降低了方法的可访问性,而这是 Java 编译器不允许的。

与 abstract 类一样,在实现接口时也可以使用 @Override。它可以防止意外重载,还可以提示读者实现的是哪些接口方法。

10.2.1 默认方法

Java 8 为 default 关键字找到了一个额外的用途 (以前只在 switch 语句和注解中使用)​。

当在接口中使用时,default 会允许方法创建一个方法体,实现了该接口的类可以在不定义方法的情况下直接替换方法体。

默认方法比抽象类上的方法更受限制,但非常有用,我们将在第 14 章中看到这一点。

让我们通过下面这个接口看看它是如何工作的:

java 复制代码
package interfaces;
// interfaces/AnInterface.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.

interface AnInterface {
  void firstMethod();
  void secondMethod();
}

可以用通常的方式来实现这个接口:

java 复制代码
package interfaces;
// interfaces/AnImplementation.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.

public class AnImplementation implements AnInterface {
  @Override public void firstMethod() {
    System.out.println("firstMethod");
  }
  @Override public void secondMethod() {
    System.out.println("secondMethod");
  }
  public static void main(String[] args) {
    AnInterface i = new AnImplementation();
    i.firstMethod();
    i.secondMethod();
  }
}
/* Output:
firstMethod
secondMethod
*/

如果将另一个方法 newMethod() 添加到 AnInterface 中,

并且没有在 AnImplementation 中为该方法提供实现,编译器就会抛出如下错误:

如果使用 default 关键字来为 newMethod() 提供默认定义,

则使用该接口的所有旧代码都可以继续工作,不用做任何变动,而新代码则可以调用 newMethod():

java 复制代码
package interfaces;
// interfaces/InterfaceWithDefault.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.

interface InterfaceWithDefault {
  void firstMethod();
  void secondMethod();
  default void newMethod() {
    System.out.println("newMethod");
  }
}

default 关键字允许我们在接口中实现方法------在 Java 8 之前这是不行的。

java 复制代码
package interfaces;
// interfaces/Implementation2.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.

public class Implementation2
implements InterfaceWithDefault {
  @Override public void firstMethod() {
    System.out.println("firstMethod");
  }
  @Override public void secondMethod() {
    System.out.println("secondMethod");
  }
  public static void main(String[] args) {
    InterfaceWithDefault i =
      new Implementation2();
    i.firstMethod();
    i.secondMethod();
    i.newMethod();
  }
}
/* Output:
firstMethod
secondMethod
newMethod
*/

尽管 newMethod() 在 Implementation2 中没有定义,但它现在是可用的。

添加默认方法的一个令人信服的原因是,它允许向现有接口中添加方法,而不会破坏已经在使用该接口的所有代码。

默认方法有时也称为防御方法 (defender method) 或虚拟扩展方法 (virtual extension method)。

在 JDK 9 中,接口里的 default 和 static 方法都可以是 private 的。

10.2.2 多重继承

多重继承意味着一个类可以从多个基类型继承特性和功能。

在最初设计 Java 时,C++ 中的多重继承正面临着严厉的批评。

Java 严格来说是一种单继承语言:只能继承一个类(或抽象类)​。

你可以实现任意数量的接口,但在 Java 8 之前,接口没有什么包袱------它只是描述了其方法是什么样的。

多年后的今天,通过默认方法,Java 拥有了多重继承的一些特性。

将接口与默认方法结合,意味着我们可以结合来自多个基类型的行为。

**因为接口仍然不允许包含字段(接口里只有静态字段,并不适用于我们这里讨论的场景)**​,

所以字段仍然只能来自单个基类或抽象类。

也就是说,你不能拥有状态的多重继承 。

下面是它的示例:

java 复制代码
package interfaces;
// interfaces/MultipleInheritance.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
import java.util.*;

interface One {
  default void first() { System.out.println("first"); }
}

interface Two {
  default void second() {
    System.out.println("second");
  }
}

interface Three {
  default void third() { System.out.println("third"); }
}

class MI implements One, Two, Three {}

public class MultipleInheritance {
  public static void main(String[] args) {
    MI mi = new MI();
    mi.first();
    mi.second();
    mi.third();
  }
}
/* Output:
first
second
third
*/

现在我们可以做一些在 Java 8 之前做不到的事情:组合多个来源的实现。

只要所有基类方法都有不同的名称和参数列表,代码就能正常工作。

如果没有,就会收到编译时错误消息:

java 复制代码
package interfaces;
// interfaces/MICollision.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
import java.util.*;

interface Bob1 {
  default void bob() {
    System.out.println("Bob1::bob");
  }
}

interface Bob2 {
  default void bob() {
    System.out.println("Bob2::bob");
  }
}

// class Bob implements Bob1, Bob2 {}
/* Produces:
error: class Bob inherits unrelated defaults
for bob() from types Bob1 and Bob2
class Bob implements Bob1, Bob2 {}
^
1 error
*/

interface Sam1 {
  default void sam() {
    System.out.println("Sam1::sam");
  }
}

interface Sam2 {
  default void sam(int i) {
    System.out.println(i * 2);
  }
}

// Works because the argument lists are distinct:
class Sam implements Sam1, Sam2 {}

interface Max1 {
  default void max() {
    System.out.println("Max1::max");
  }
}

interface Max2 {
  default int max() { return 47; }
}

class Max implements Max1, Max2 {}
/* Produces:
error: types Max2 and Max1 are incompatible;
both define max(), but with unrelated return types
class Max implements Max1, Max2 {}
^
1 error
*/

在 Sam 类中,两个 sam() 方法具有相同的名称,但它们的方法签名是唯一的------签名包括名称和参数类型 ,

编译器用它来区分不同的方法。但是,正如 Max 类所示,返回类型不是方法签名的一部分,因此不能用于区分两个方法。

要解决这个问题,就必须重写冲突的方法:

java 复制代码
// interfaces/Jim.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
import java.util.*;

interface Jim1 {
  default void jim() {
    System.out.println("Jim1::jim");
  }
}

interface Jim2 {
  default void jim() {
    System.out.println("Jim2::jim");
  }
}

public class Jim implements Jim1, Jim2 {
  @Override 
  public void jim() {
    Jim2.super.jim();
  }
  public static void main(String[] args) {
    new Jim().jim();
  }
}
/* Output:
Jim2::jim
*/

当然,你可以将 jim() 重新定义为任何东西,但通常会使用 super 关键字来选择一个基类实现,就像上面所示的那样。

10.2.3 接口中的静态方法

Java 8 还可以在接口中包含静态方法。

这允许我们在接口里包含逻辑上属于它的实用程序。

这些实用程序通常是像 runOps() 这种操作该接口的方法,或者 show() 这样的通用工具:

java 复制代码
// onjava/Operation.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
package onjava;

public interface Operation {
  void execute();
  static void runOps(Operation... ops) {
    for(Operation op : ops)
      op.execute();
  }
  static void show(String msg) {
    System.out.println(msg);
  }
}

runOps() 是模板方法 (Template Method) 设计模式的一个例子,在进阶卷第 8 章中有描述。

runOps() 使用可变参数列表,因此我们可以根据需要传递任意数量的 Operation 参数,并按顺序运行它们,如 main() 方法所示:

java 复制代码
package interfaces;
// interfaces/MetalWork.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
import onjava.Operation;

class Heat implements Operation {
  @Override public void execute() {
    Operation.show("Heat");
  }
}

public class MetalWork {
  public static void main(String[] args) {
    // Must be defined in a static context
    // to access a method reference:
    Operation twist = new Operation() {
      public void execute() {
        Operation.show("Twist");
      }
    };
    Operation.runOps(
      new Heat(),                     // [1]
      new Operation() {               // [2]
        public void execute() {
          Operation.show("Hammer");
        }
      },
      twist::execute,                 // [3]
      () -> Operation.show("Anneal")  // [4]
    );
  }
}
/* Output:
Heat
Hammer
Twist
Anneal
*/

在这里,可以看到创建 Operation 实现类的不同方式。

1 常规类 Heat。

2 匿名类。

3 方法引用。

4 Lambda 表达式------需要最少的代码。

此功能是一项改进,因为它允许将静态方法放在更合适的位置。

10.2.4 作为接口的 Instrument

由于接口的工作方式,Instrument 中的任何方法都没有被明确定义为 public,但无论如何它们都自动就是 public 的。

play() 和 adjust() 都使用了 default 关键字来定义。

在 Java 8 之前,这两个定义必须在每个实现中重复,这样很明显既多余又烦人:

java 复制代码
// interfaces/music5/Music5.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// {java interfaces.music5.Music5}
package interfaces.music5;
import polymorphism.music.Note;

interface Instrument {
  // Compile-time constant:
  int VALUE = 5; // static & final
  default void play(Note n) {  // Automatically public
    System.out.println(this + ".play() " + n);
  }
  default void adjust() {
    System.out.println("Adjusting " + this);
  }
}

class Wind implements Instrument {
  @Override public String toString() {
    return "Wind";
  }
}

class Percussion implements Instrument {
  @Override public String toString() {
    return "Percussion";
  }
}

class Stringed implements Instrument {
  @Override public String toString() {
    return "Stringed";
  }
}

class Brass extends Wind {
  @Override public String toString() {
    return "Brass";
  }
}

class Woodwind extends Wind {
  @Override public String toString() {
    return "Woodwind";
  }
}

public class Music5 {
  // Doesn't care about type, so new types
  // added to the system still work right:
  static void tune(Instrument i) {
    // ...
    i.play(Note.MIDDLE_C);
  }
  static void tuneAll(Instrument[] e) {
    for(Instrument i : e)
      tune(i);
  }
  public static void main(String[] args) {
    // Upcasting during addition to the array:
    Instrument[] orchestra = {
      new Wind(),
      new Percussion(),
      new Stringed(),
      new Brass(),
      new Woodwind()
    };
    tuneAll(orchestra);
  }
}
/* Output:
Wind.play() MIDDLE_C
Percussion.play() MIDDLE_C
Stringed.play() MIDDLE_C
Brass.play() MIDDLE_C
Woodwind.play() MIDDLE_C
*/

这个版本的示例还有另一个更改:

what() 方法更改为 toString()。之所以这样修改,是因为该方法的用途。

toString() 是根类 Object 的一部分,因此不必出现在接口里。

请注意,不管是向上转型到常规类 Instrument,还是抽象类 Instrument,或者接口 Instrument,行为都是一样的。

事实上,tune() 方法里没有任何信息来说明 Instrument 是常规类、抽象类还是接口。

10.3 抽象类与接口

特别是在 Java 8 中添加了默认方法后,在抽象类和接口中如何选择变得有些令人困惑。

表 10-1 可以将它们清楚地区分开来。

表 10-1

特性 接口 抽象类
组合 可以在新类中组合多个接口 只能继承一个抽象类
状态 不能包含字段(静态字段除外,但它们不支持对象状态) 可以包含字段,非抽象方法可以引用这些字段
默认方法与抽象方法 默认方法不需要在子类型里实现,它只能引用接口里的方法(字段不行) 抽象方法必须在子类型里实现
构造器 不能有构造器 可以有构造器
访问权限控制 隐式的 public 可以为 protected 或包访问权限

抽象类仍然是一个类,因此如果被创建的新类所继承,则该抽象类就应该是唯一被继承的类。

在创建新类的过程中可以实现多个接口。

一个经验法则是 "在合理的范围内尽可能抽象"​。

因此,和抽象类相比,我们更偏向于使用接口。

当必须使用抽象类的时候,你自然就会知道。

除非必需,否则两个都不要使用。

大多数情况下,常规类就可以解决问题,如果不能,可以再使用接口或抽象类。

10.4 完全解耦

当方法与类而不是接口配合使用时,你就只能使用该类或其子类。

如果想将该方法应用于不在这个继承层次结构的类上,那你就束手无策了。

而接口大大放宽了这种限制,因此可以编写更多可复用的代码。

例如,假设有一个 Processor 类,它有两个方法 name() 和 process()。

process() 接受输入,修改后再输出。

你可以继承此类来创建不同类型的 Processor。

这里,这些 Processor 类型修改了字符串对象(注意返回类型可以是协变的,但参数类型不行)​:

java 复制代码
package interfaces;
// interfaces/Applicator.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
import java.util.*;

class Processor {
  public String name() {
    return getClass().getSimpleName();
  }
  public Object process(Object input) {
    return input;
  }
}

class Upcase extends Processor {
  @Override // Covariant return:
  public String process(Object input) {
    return ((String)input).toUpperCase();
  }
}

class Downcase extends Processor {
  @Override
  public String process(Object input) {
    return ((String)input).toLowerCase();
  }
}

class Splitter extends Processor {
  @Override
  public String process(Object input) {
    // split() divides a String into pieces:
    return Arrays.toString(((String)input).split(" "));
  }
}

public class Applicator {
  public static void apply(Processor p, Object s) {
    System.out.println("Using Processor " + p.name());
    System.out.println(p.process(s));
  }
  public static void main(String[] args) {
    String s =
      "We are such stuff as dreams are made on";
    apply(new Upcase(), s);
    apply(new Downcase(), s);
    apply(new Splitter(), s);
  }
}
/* Output:
Using Processor Upcase
WE ARE SUCH STUFF AS DREAMS ARE MADE ON
Using Processor Downcase
we are such stuff as dreams are made on
Using Processor Splitter
[We, are, such, stuff, as, dreams, are, made, on]
*/

Applicator.apply() 方法接受任何类型的 Processor,调用其 process() 传入 Object 类型参数 s 并打印结果。

可以创建这样一个方法,它根据传递的参数对象来表现出不同的行为,这就是策略 (Strategy) 设计模式 。

方法包含了算法的固定部分,而策略包含了变化的部分。

策略是你传入的对象,其中包含代码。

这里 Processor 对象是策略,main() 方法里显示了应用于字符串 s 的三种策略。

split() 方法是 String 类的一部分。它接受一个字符串对象并使用参数作为边界符将其拆分,然后返回一个 String​​。

这里用它可以更简便地创建 String 数组。

现在假设你发现了一组电子过滤器,它们看起来可能适合 Applicator.apply() 方法:

java 复制代码
// interfaces/filters/Filter.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
package interfaces.filters;

public class Filter {
  public String name() {
    return getClass().getSimpleName();
  }
  public Waveform process(Waveform input) {
    return input;
  }
}
java 复制代码
// interfaces/filters/BandPass.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
package interfaces.filters;

public class BandPass extends Filter {
  double lowCutoff, highCutoff;
  public BandPass(double lowCut, double highCut) {
    lowCutoff = lowCut;
    highCutoff = highCut;
  }
  @Override
  public Waveform process(Waveform input) {
    return input;
  }
}
java 复制代码
// interfaces/filters/HighPass.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
package interfaces.filters;

public class HighPass extends Filter {
  double cutoff;
  public HighPass(double cutoff) {
    this.cutoff = cutoff;
  }
  @Override
  public Waveform process(Waveform input) {
    return input;
  }
}
java 复制代码
// interfaces/filters/LowPass.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
package interfaces.filters;

public class LowPass extends Filter {
  double cutoff;
  public LowPass(double cutoff) {
    this.cutoff = cutoff;
  }
  @Override
  public Waveform process(Waveform input) {
    return input; // Dummy processing
  }
}
java 复制代码
// interfaces/filters/Waveform.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
package interfaces.filters;

public class Waveform {
  private static long counter;
  private final long id = counter++;
  @Override public String toString() {
    return "Waveform " + id;
  }
}

Filter 与 Processor 具有相同的接口元素,

但因为 Filter 类的创建者并不知道你可能想把它当 Processor 来使用,所以它没有继承 Processor,

这样你就不能在 Applicator.apply() 方法里使用 Filter 了,即使它能正常工作。

基本上,Applicator.apply() 和 Processor 之间的耦合超过了所需的程度,这阻止了 Applicator.apply() 代码的复用---在它本可以被复用的时候。另外请注意,输入和输出参数都是 Waveform。

但是,如果 Processor 是一个接口,那么约束就足够宽松,你就可以复用参数为该接口类型的 Applicator.apply() 方法了。

以下是 Processor 和 Applicator 的修改版本:

java 复制代码
// interfaces/interfaceprocessor/Processor.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
package interfaces.interfaceprocessor;

public interface Processor {
  default String name() {
    return getClass().getSimpleName();
  }
  Object process(Object input);
}
java 复制代码
// interfaces/interfaceprocessor/Applicator.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
package interfaces.interfaceprocessor;

public class Applicator {
  public static void apply(Processor p, Object s) {
    System.out.println("Using Processor " + p.name());
    System.out.println(p.process(s));
  }
}

复用代码的第一种方法是,调用者可以编写符合这个接口的类,如下所示:

java 复制代码
// interfaces/interfaceprocessor/StringProcessor.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// {java interfaces.interfaceprocessor.StringProcessor}
package interfaces.interfaceprocessor;
import java.util.*;

interface StringProcessor extends Processor {
  @Override
  String process(Object input);        // [1]
  String S =                           // [2]
  "If she weighs the same as a duck, " +
  "she's made of wood";
  static void main(String[] args) {    // [3]
    Applicator.apply(new Upcase(), S);
    Applicator.apply(new Downcase(), S);
    Applicator.apply(new Splitter(), S);
  }
}

class Upcase implements StringProcessor {
  @Override // Covariant return:
  public String process(Object input) {
    return ((String)input).toUpperCase();
  }
}

class Downcase implements StringProcessor {
  @Override
  public String process(Object input) {
    return ((String)input).toLowerCase();
  }
}

class Splitter implements StringProcessor {
  @Override
  public String process(Object input) {
    return Arrays.toString(((String)input).split(" "));
  }
}
/* Output:
Using Processor Upcase
IF SHE WEIGHS THE SAME AS A DUCK, SHE'S MADE OF WOOD
Using Processor Downcase
if she weighs the same as a duck, she's made of wood
Using Processor Splitter
[If, she, weighs, the, same, as, a, duck,, she's, made,
of, wood]
*/

1 这个声明是不必要的,如果删除它,编译器也不会提示错误。但它能指出方法的返回值从 Object 协变为 String。

2 字段 s 自动是 static 和 final 的,因为它是在接口内定义的。

3 你甚至可以在接口中定义一个 main() 方法。

在这里,这种处理方式是有效的。但是你经常会遇到无法修改类的情况。

以上面的电子过滤器为例,库一般是被发现而不是被创建的。

在这些情况下,可以使用适配器 (Adapter) 设计模式。

在适配器里,编写代码来通过已有的接口生成需要的接口,如下所示:

java 复制代码
// interfaces/interfaceprocessor/FilterProcessor.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// {java interfaces.interfaceprocessor.FilterProcessor}
package interfaces.interfaceprocessor;
import interfaces.filters.*;

class FilterAdapter implements Processor {
  Filter filter;
  FilterAdapter(Filter filter) {
    this.filter = filter;
  }
  @Override
  public String name() { return filter.name(); }
  @Override
  public Waveform process(Object input) {
    return filter.process((Waveform)input);
  }
}

public class FilterProcessor {
  public static void main(String[] args) {
    Waveform w = new Waveform();
    Applicator.apply(
      new FilterAdapter(new LowPass(1.0)), w);
    Applicator.apply(
      new FilterAdapter(new HighPass(2.0)), w);
    Applicator.apply(
      new FilterAdapter(new BandPass(3.0, 4.0)), w);
  }
}
/* Output:
Using Processor LowPass
Waveform 0
Using Processor HighPass
Waveform 0
Using Processor BandPass
Waveform 0
*/

在使用适配器的实现方式里,FilterAdapter 构造器通过你拥有的 Filter 接口,来生成一个你需要的 Processor 接口的对象。

你可能还会注意到 FilterAdapter 类中使用了委托。

协变允许我们从 process() 里产生一个 Waveform,而不仅仅是一个 Object。

接口与实现的解耦允许我们将一个接口应用于多个不同的实现,因此代码更具可复用性。

相关推荐
CoderYanger41 分钟前
Java EE 进阶:9.MyBatis 操作数据库(进阶)(第八弹):MyBatis Generator
java·数据库·spring boot·spring·java-ee·tomcat·mybatis
Thanks_ks1 小时前
AI Agent 开发入门:用 Function Calling 让大模型学会 “动手干活”,附订单查询机器人实战
python·ai·大模型·openai·agent·通义千问·mcp
专注仿真1 小时前
智能体训练之模仿学习:GAIL 算法详解与实战
python·算法·仿真·多智能体强化学习·afsim智能体训练
databook2 小时前
处理一批 PDF,怎么算真的处理完了
后端·python
jaysee-sjc3 小时前
【黑马点评】Day02:优惠券秒杀与分布式锁
java·分布式·nginx·spring·node.js·tomcat·maven
承渊政道4 小时前
【Python编程快速上手—让繁琐工作自动化】(列表:把数据排成队,从下标取值到深拷贝)
开发语言·python·pycharm·自动化·列表
秋天的怀念_David4 小时前
算法一千零一夜 · 第三十五夜 · 恢复风暴
java·程序人生·算法
考虑考虑4 小时前
JDK27中的加密对象的 PEM 编码
java·后端·java ee
大胖爱学习_MJ4 小时前
Agent 如何安全地拿数据库密码?基于 HashiCorp Vault 的动态凭证下发
经验分享·python