请问以下界面mindroid/os/IRemoteCallback.java中使用的设计模式的名称和目的是什么?
为什么在界面中定义了3个类(Stub
,Proxy
,SmartProxy
)?
public interface IRemoteCallback extends IInterface {
public static abstract class Stub extends Binder implements IRemoteCallback {
private static final String DESCRIPTOR = "mindroid.os.IRemoteCallback";
public Stub() {
this.attachInterface(this, DESCRIPTOR);
}
public static IRemoteCallback asInterface(IBinder binder) {
if (binder == null) {
return null;
}
return new IRemoteCallback.Stub.SmartProxy(binder);
}
public IBinder asBinder() {
return this;
}
protected Object onTransact(int what, int arg1, int arg2, Object obj, Bundle data) throws RemoteException {
switch (what) {
case MSG_SEND_RESULT: {
sendResult(data);
return null;
}
default:
return super.onTransact(what, arg1, arg2, obj, data);
}
}
private static class Proxy implements IRemoteCallback {
private final IBinder mRemote;
Proxy(IBinder remote) {
mRemote = remote;
}
public IBinder asBinder() {
return mRemote;
}
public void sendResult(Bundle data) throws RemoteException {
mRemote.transact(MSG_SEND_RESULT, data, FLAG_ONEWAY);
}
}
private static class SmartProxy implements IRemoteCallback {
private final IBinder mRemote;
private final IRemoteCallback mStub;
private final IRemoteCallback mProxy;
SmartProxy(IBinder remote) {
mRemote = remote;
mStub = (IRemoteCallback) remote.queryLocalInterface(DESCRIPTOR);
mProxy = new IRemoteCallback.Stub.Proxy(remote);
}
public IBinder asBinder() {
return mRemote;
}
public void sendResult(Bundle data) throws RemoteException {
if (mRemote.runsOnSameThread()) {
mStub.sendResult(data);
} else {
mProxy.sendResult(data);
}
}
}
static final int MSG_SEND_RESULT = 1;
}
public void sendResult(Bundle data) throws RemoteException;
}
我很难理解并使用上述代码。
我唯一注意到的是检查调用者是否在同一个线程,如果没有 - 通过处理程序将消息发送到Proxy
类。
此外,我认为可以在不同的线程中使用字符串(此处为DESCRIPTOR
常量)来获取IInterface。
更新
作者在此回复:
它是关于在正确的线程上下文中运行Callback,这是 创建回调的上下文。 SmartProxy类首先检查它是线程本地调用还是远程调用 (线程间)调用。 然后直接调用方法(使用Stub)或者它 消息传递切换到正确的线程上下文(使用代理)。