[英]Concrete class implements an interface which knows the concrete class that implement it
[英]Passing arguments - interface implementation vs object of concrete class which implements the interface
考虑 OnCompleteListener 是一个接口,而 OnCompleteListenerImpl 是一个具体的 class 如下
### 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);
两者的方法相似,但两者之间存在很大差异
可用性
总而言之,这两种方法都有不同的用例,取决于您要遵循哪种方法。 For clean code and reusability, we go with implementation class but in case of secure and single instance use, you can go with anonymous class approach.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.