我读this和this,发现在类B
我需要保存对类A
的引用,并且当类B
中发生什么时,我们执行一个由类A
实现的接口定义的方法。好吧,我理解它。我使用的接口在有些不同的方式来调用回调:这是使用接口回调的正确方法吗?
interface IHelper {
void onActionDone();
void onActionFailed();
}
public class Helper implements IHelper {
public Helper (Param param) {
// here we do what Helper class intended to do
// ...
// now call the any of callbacks
if(everything == OK) {
onActionDone();
} else {
onActionFailed();
}
}
@Override
public void onActionDone() {}
@Override
public void onActionFailed() {}
}
public class MainClass() {
new Helper(message) {
public void onActionDone() {
// here we can do anything we want after Helper will done its functions
}
public void onActionFailed() {
// or not done
}
}
}
,我觉得这种方式更容易阅读和理解,但不知道这是一个不好的做法与否。那么我可以随意进一步走这条路吗?
刚才发现我在这种情况下甚至不需要接口。所以在我看来,这是做回调的不好的方法( – kolyaseg
_“刚刚发现我在这种情况下甚至不需要接口。”)_在这种情况下,您可以使用NONE类实例,而是使用'Helper'实例以通知MainClass中发生的完成/失败操作,这会使这些类紧密耦合在一起,你的代码变得更加灵活和难以维护,相反,通过使用'Observer'模式,你可以使用任何实现类的实现'IHelper'接口,这使得类间松散耦合,代码看起来更加灵活。 – Onik