有问题的模式涉及一个抽象类,它有一个方法可以完成一些工作,然后调用一个抽象方法.该类通过在匿名类中进行子类化并指定抽象方法的行为来使用.一个例子:
/* The abstract class */
abstract class WebCall {
String url;
WebCall(String url) {
this.url = url;
}
void call() {
// Make call to url
// Callback
if (worked) {
success();
} else {
failure();
}
}
protected abstract void success();
protected abstract void failure();
}
Run Code Online (Sandbox Code Playgroud)
你会像这样使用这个类:
new WebCall(someUrl) {
@Override
protected void success() {
// Implementation
}
@Override
protected void failure() {
// Implementation
}
}.call();
Run Code Online (Sandbox Code Playgroud)
一个真实世界的例子是来自Android的AsyncTask.这种模式有一个共同的名称吗?