如何“传递接口”,即CommonsWare向以下问题?>中的询问者建议了什么?
另一种方法是将DownloadFileTask公之于众,并将某些内容传递给构造函数。在这种情况下,为了最小化耦合,您可能不想传递一个活动,,而是一些限制AsyncTask可以做什么的其他类型的接口。通过这种方式,您可以选择在一个活动上实现接口,或者作为一个单独的对象来实现,或者其他什么。-4月27日下午17:44 CommonsWare
如何允许线程只访问某些(或仅仅一个)对象--公共方法?
Answer>见下面的答案。
真正的问题是我对接口所做的事情的误解。如果将方法F(或类的参数化)的输入类型指定为接口,即F(my_interface i),并且将对象X传递给实现my_interface F(X)的方法,那么即使存在其他成员,也只有实现my_interface的X成员才能被方法F访问。
我认为接口只对实现类施加了约束。我不明白当接口被用作一种类型时,它也会限制对实现类成员的访问。回顾一下,考虑到Java是静态类型的,这是显而易见的。有关更多信息,请参见Java教程。
发布于 2011-07-07 18:33:17
假设您需要能够报告某些后台任务的步骤。您可以通过更改标签的文本或更改通知泡的文本来选择。
一种方法是将标签或通知传递给后台任务:
public class BackgroundTask {
private Label labelToUpdate;
private Notification notificationToUpdate;
public BackgroundTask(Label label) {
this.labelToUpdate = label;
}
public BackgroundTask(Notification notification) {
this.notificationToUpdate = notification;
}
//...
private void reportNewStep(String step) {
if (labelToUpdate != null) {
labelToUpdate.setText(step);
}
if (notificationToUpdate != null) {
notificationToUpdate.alert(step);
}
}
}这将BackgroundTask与UI结合在一起,并与报告进度的两种可能方法结合在一起。如果添加第三个,则必须更改BackGroundTask的代码。
现在提取一个接口:
public interface ProgressListener {
void report(String step);
}
public class BackgroundTask {
private ProgressListener listener;
public BackgroundTask(ProgressListener listener) {
this.listener = listener;
}
//...
private void reportNewStep(String step) {
listener.report(step);
}
}BackgroundTask现在更简单了,不再依赖于报告进度的所有可能方法。调用者只需给它一个ProgressListener接口的实现。对于基于标签的进度,它将执行以下操作:
BackgroundTask task = new BackgroundTask(new ProgressListener() {
@Override
public void report(String step) {
label.setText(step);
}
});或者您的活动可以直接实现ProgressListener:
public class MyActivity implements ProgressListener {
private Notification notification;
// ...
@Override
public void report(String step) {
notification.alert(step);
}
// ...
BackgroundTask backgroundTask = new BackgroundTask(this);
}标签和BackgroundTask之间,或者MyActivity和BackgroundTask之间不再耦合。BackgroundTask不能再调用任何标签、通知或MyActivity方法。它只能调用它应该调用的东西:专用ProgressListener接口的方法。
https://stackoverflow.com/questions/6615079
复制相似问题