首页 > 新闻系统 > 编程天地 > 文章正文

Java Q&A: 抽象类和接口实例学习

2007-12-12 13:31:53 来源:中国自学编程网 作者:转载 点击:
在Java中,什么时候该用抽象类,什么时候该用接口?下面的文章将通过实例,而不是从理论的角度给你一个清晰的回答,让你有可能获得醍醐灌顶般的彻悟。以下是原文翻译。

  
  MessageBus使得你可以在支持MessageBus的程序中增加新的通信机制;与此类似,Message使得你任何时候可以在程序中增加新的Message类型。
  
  HttpMessageBus 
  
  看下面一个具体的MessageBus实现,它通过HTTP来POST消息:
  
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.NET.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.net.URLEncoder;
/**
* HttpMessageBus是一个MessageBus实现,
* 它采用HTTP POST来发送消息。
* @author  Tony Sintes JavaWorld Q&A
*/
public class HttpMessageBus implements MessageBus {
  private String _url;
  
  private final static String _KEY_VALUE_DELIM = "=";
  private final static String _NEW_KEY_VALUE  = "&";
  private final static String _ENCODING = "application/x-www-form-urlencoded";
  private final static String _TYPE  = "Content-Type";
  private final static int _KEY  = 0;
  private final static int _VALUE = 1;
  
  public HttpMessageBus( String url ) 
  {
  _url = url;
  }
  public String sendMessage( String[][] values ) throws BusException 
  {
  String post = _formulatePOST( values ); 
  try 
  {
  return _sendPOST( post );
  } 
  catch( MalformedURLException exception ) 
  {
  throw new HttpBusException( exception.getMessage() );
  } 
  catch( IOException exception ) 
  {
  throw new HttpBusException( exception.getMessage() );
  }
  }
  
  private String _formulatePOST( String [][] values ) {
  if( ( values == null ) || ( values.length == 0 ) ) 
  {
  return "";
  }
  
  StringBuffer sb = new StringBuffer();
  String new_pair = "";
  
  for( int i = 0; i < values.length; i ++ ) 
  {
  sb.append( new_pair );
  sb.append( URLEncoder.encode( values[i][_KEY] ) ); 
  sb.append( _KEY_VALUE_DELIM ); 
  sb.append( URLEncoder.encode( values[i][_VALUE] ) );
  new_pair = _NEW_KEY_VALUE;
  }
  
  String post = sb.toString();
  return post;
  }
  
  private String _sendPOST( String post ) throws MalformedURLException, IOException 
  {  
  URLConnection conn = _setUpConnection();
  _write( post, conn );
  return _read( conn );
  }
  
  private URLConnection _setUpConnection() throws MalformedURLException, IOException 
  { 
  URL url = new URL( _url );
  URLConnection conn = url.openConnection();
  
  conn.setDoInput ( true );
  conn.setDoOutput ( true );
  conn.setUseCaches ( false );
  conn.setRequestProperty( _TYPE, _ENCODING );
  
  return conn;
  }
  
  private void _write( String post, URLConnection conn ) throws IOException
  {
  DataOutputStream output = new DataOutputStream ( conn.getOutputStream() );
  output.writeBytes( post );
  output.flush ();
  output.close ();  
 
9 7 3 1 2 3 4 5 4 8 :

精彩推荐
焦点大图推荐
本类热门文章

论坛美图

本周软件下载排行

广告联系 | 版权说明 | 意见建议 | 加入收藏 | 军网站群 [ 军软件园 - 军软件商城 - 军软件园论坛 ]

电信与信息服务业务经营许可证:京ICP证050203