标签:设计模式
序言(1)Main函数:
[java] view plain copy
<span style="font-size:18px;">package tgb;
public class Main {
public static void main(String[] args){
Client client = new Client();
//理解返回一个FutureData
Data data = client.request("name");
System.out.println("请求完毕!");
try{
//处理其他业务
//这个过程中,真是数据RealData组装完成,重复利用等待时间
Thread.sleep(2000);
}catch (Exception e){
}
//真实数据
System.out.println("数据 = "+ data.getResult());
}
}
</span>
(2)Client的实现:
[java] view plain copy
<span style="font-size:18px;">package tgb;
public class Client {
public Data request(final String queryStr){
final FutureData future = new FutureData();
//开启一个子线程来构造真实数据
new Thread(){
public void run(){
RealData realData = new RealData(queryStr);
future.setRealData(realData); }
}.start();
return future;
}
}
</span>
(3)Data的实现:
[java] view plain copy
<span style="font-size:18px;">package tgb;
public interface Data {
public String getResult();
}
</span>
(4)FutureData:
[java] view plain copy
<span style="font-size:18px;">package tgb;
/**
*/
public class FutureData implements Data {
protected RealData realData =null;
protected boolean isReady = false;
public synchronized void setRealData(RealData realData){
if(isReady){
return;
}
this.realData=realData;
isReady=true;
notifyAll();
}
@Override
public synchronized String getResult() {
while(!isReady){
try{
wait();
}catch (Exception e){
}
}
return realData.result;
}
}
</span>
(5)RealData实现:
[java] view plain copy
<span style="font-size:18px;">package tgb;
public class RealData implements Data {
protected String result;
public RealData(String para){
//耗时的操作 用Thread.sleep代替一下
StringBuffer sb= new StringBuffer();
for(int i=0;i<10;i++){
sb.append(para);
try{
Thread.sleep(1000);
}catch(Exception e){
}
result= sb.toString();
}
}
@Override
public String getResult() {
return result;
}
}
</span>
注意:
注意真正处理的代码是 RealData ,所以当 RealData抛出异常的时候,一定要注意处理!具体怎么处理就要看业务场景了。
标签:设计模式
原文地址:http://blog.51cto.com/13666149/2091152