【问题标题】:What is interface and wrapper?什么是接口和包装器?
【发布时间】:2012-12-06 03:09:26
【问题描述】:

我知道为什么要使用接口和包装器。

但我混淆命名包装类...(“谁是包装?”我知道我不太清楚...)

public Interface A {
    void method();
}

public Class B implements A {
    void method() {
        doSomething();
    }
}

我对两件事感到困惑......

  1. Wrapper Class 是 class ,所以 B 是 wrapper。

  2. 我们通常看到(或认为?)a.method() 而不是 b.method(),所以 A 是包装器。

什么是包装器?

一个?乙?

还有……

如何使用“Wrapper”或“W”命名 A、B 好?

A,AWrapper?还是 B,BWrapper?还是其他人...?

【问题讨论】:

    标签: java design-patterns interface wrapper


    【解决方案1】:

    A 是一个接口。 BInterface 的具体实现。从您提供的代码中无法说明其他任何内容。

    Wrapper 通过添加或简化包装类/API 的功能来“包装”另一个类或 API 的功能。例如,Java 中的Primitive WrappersdoubleValuecompareTo 等有用的方法添加到Java 原语中。

    你在想Polymorphism

    这让我们可以说:

    A a = new B();
    B b = new B();
    List<A> stuffs = new ArrayList<A>();
    stuffs.add(b);
    

    旁注:

    InterfaceClass 在 Java 中不允许大写。你的声明应该是这样的:

    public interface A {
      // methods
    }
    
    public class B implements A {
      // methods
    }
    

    【讨论】:

    • 谢谢!你知道其他例子(不是原始包装器)吗?
    【解决方案2】:

    您的示例中的 A 或 B 都不能称为包装器。 A 和 B 的关系是Inheritance。一个Wrapper 类通常是contains 一个或多个Wrappee 对象。适配器和外观模式是很好的包装器示例。

    有关 Wrappers 的详细讨论,请参阅 this

    【讨论】:

      猜你喜欢
      • 2012-12-03
      • 2020-10-05
      • 2013-11-17
      • 2012-06-28
      • 1970-01-01
      • 2012-01-27
      • 1970-01-01
      • 2020-02-02
      • 2012-06-12
      相关资源
      最近更新 更多