与其他语言一样,我们可以在initialization
. 请帮帮我我该怎么办?
例如:
public class DemoInitAndOverride {
public void handleMessage(){}
}
在另一个班级
public class SampleClass {
public void doSomeThing(){
DemoInitAndOverride demo = new DemoInitAndOverride(){
@Override
public void handleMessage() {
// TODO Auto-generated method stub
super.handleMessage();
}
};
}
}
****EDIT:****
感谢大家提供可能的解决方案和建议。我认为现在对我来说重要的是提供一些有关需求的详细信息,这可以帮助您提供解决方案。
处理程序的概念类似于 Android 框架,其中处理程序用于在 2 个线程或 2 个方法之间传递消息。请看下面的代码演示:
UI 类(这里用户单击一个按钮,使用处理程序将请求分派到处理器类)
这是演示处理程序
/**
*
* Used for thread to thread communication.
* Used for non UI to UI Thread communication.
*
*/
public class DemoHandler {
public void handleMessage(Messages message){}
final public void sendMessage(final Messages message){
//Calling thread is platform dependent and shall change based on the platform
new Thread(new Runnable() {
@Override
public void run() {
synchronized (this) {
handleMessage(message);
}
}
});
}
}
这是简单的消息类
public class Messages {
public Object myObject;
//other hash map (key, values) and get data put data etc
}
这是简单的用户界面类演示代码:
public class UIClass {
public UIClass(){
//INIT
}
void onClick(int id){
//Some Button is clicked:
//if id == sendParcel
//do
TransactionProcessor.getInstance().sendParcel(handler, "Objects");
}
DemoHandler handler = new DemoHandler(){
public void handleMessage(Messages message) {
//Inform the UI and Perform UI changes
//data is present in the messages
};
};
}
这是示例事务处理器类
公共类事务处理器 {
public static TransactionProcessor getInstance(){
return new TransactionProcessor(); //for demonstration
}
//Various Transaction Methods which requires calling server using HTTP and process there responses:
public void sendParcel(final DemoHandler uiHander, String otherdetailsForParcel){
//INIT Code and logical code
//Logical Variables and URL generation
String computedURL = "abc.com/?blah";
DemoHandler serverConnectionHandler = new DemoHandler(){
@Override
public void handleMessage(Messages message) {
super.handleMessage(message);
//Process server response:
//create a new message for the UI thread and dispatch
Messages response = new Messages();
//add details to messages
//dispatch
uiHander.sendMessage(response );
}
};
new Thread(new ServerConnection(computedURL, serverConnectionHandler));
}
public void sendEmail(final DemoHandler uiHander, String otherdetailsForEmail){
//SAME AS SEND PARCEL WITH DIFFERENT URL CREATION AND RESPONSE VALIDATIONS
}
public void sendNotification(final DemoHandler uiHander, String otherdetailsForNotifications){
//SAME AS SEND PARCEL WITH DIFFERENT URL CREATION AND RESPONSE VALIDATIONS
}
}