【问题标题】:Passing arguments - interface implementation vs object of concrete class which implements the interface传递参数 - 接口实现与实现接口的具体类的对象
【发布时间】:2019-11-01 09:34:25
【问题描述】:

考虑到 OnCompleteListener 是一个接口,而 OnCompleteListenerImpl 是一个具体类如下

### OnCompleteListener 接口####

public interface OnCompleteListener {

    public void onComplete();
}

#### OnCompleteListenerImpl ####

class OnCompleteListenerImpl  implements OnCompleteListener {
    public void onComplete() {    
        System.out.println("Yeah, the long running task has been completed!");
    }
}

这是怎么回事

#### 片段 A #####

longRunningTask.setOnCompleteListener(new OnCompleteListener() {

        @Override
        public void onComplete() {
            System.out.println("Yeah, the long running task has been completed!");
        }
    }
);

不同于

#### 片段 B ######

OnCompleteListenerImpl obj = new OnCompleteListenerImpl();

longRunningTask.setOnCompleteListener(obj);

【问题讨论】:

标签: java


【解决方案1】:

两者的方法相似,但有很大的不同

可用性

  1. OnCompleteListenerImpl 类可重用,您无需在多个地方覆盖同一个对象
  2. 初始化 OnCompleteListenerImpl 对象时需要小心,因为您可以通过多种方式进行初始化,因此必须注意其范围。
  3. 如果您使用匿名方法,则无需创建新的实现类。

总之,这两种方法都有不同的用例,取决于您要遵循哪种方法。对于干净的代码和可重用性,我们使用实现类,但在安全和单实例使用的情况下,您可以使用匿名类方法。

【讨论】:

    猜你喜欢
    • 2020-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-23
    • 2020-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多