Java Q & A: Abstract and Interface - Practical Practice

zhaozj2021-02-11  186

Java Q & A: Abstract and Interface - Practical Practice

In Java, when should I use the abstract class, when should I use? The following article will pass an instance, not from the theory's angle, so that you may get a thorough understanding of 醍醐 醍醐. The following is a text translation.

-------------------------------------------------- -

In accordance with the "Abstract and Interface" in April 2001, the reader gave positive feedback.

One requirement, which is often mentioned is that it is desirable to provide a complete example, which will be how to use the interface and abstract class (Abstract Class). It seems that my last answer is too theoretical. So, in this Java Q & A topic, I will continue to deepen this discussion through a program instance that uses interfaces and abstract classes.

When there is a network communication programming, everyone will find that communication is often done by "Key / Value PAIR," said "key / value pair"). Both HTTP POST and HTTP GET use "key / value pair" communication. The EAI server communication like WebMethod, "Key / Value" communication is also a choice mechanism. "Key / Value Pair" can also be seen even when using Java features. "Key / value pair" is everywhere.

The "key / value pair" communication is common, where it can impart data by a simple mechanism. Although it is simple, for each protocol, the way "key / value pair" data is placed on the line is different. If you want to communicate with the web server, you will use the UrlConnection to make HTTP connections. Other types of communications require you to use some other way. In this topic, I will demonstrate how to use interfaces and abstraction classes to generate a program framework, allowing this program to communicate with any server that supports the "key / value" message.

The "key / value pair" communication can extract two abstractions. First, the "key / value pair" data transmitted to the recipient constitutes a Message. Second, the message is transmitted to the server through some protocol. This protocol can be abstract as MessageBus. So, if you want to communicate with the web server, you can transfer messages via HTTP MessageBus.

The message transmitted and the mechanism of transmitting messages changes frequently, and at least different programs are like this. When you confident that something will change frequently, it is the best choice for the interface.

The following one by one, analyzes the various interfaces required for our message sender.

Messagebus can be seen from the code below that MessageBus knows that it can transmit a "key / value pair" of a two-dimensional array type to a recipient. But note that this interface does not say how to transfer or transfer it. Instead, these details are left to implementation of this interface:

Public interface messagebus {public string sentmessage (string "[] value value) throws busexception;

This interface is very powerful. You can use UrlConnections to implement it for HTTP communication; you can also implement it with a Socket, you can implement it with a custom protocol; you can only record the data into a normal file or database.

In short, this interface allows you to build a variety of different implementations. Furthermore, using interfaces rather than a particular implementation, you can enjoy the benefits of multi-state, you can replace a variety of different implementations in your program.

For example, when you want to debug a program, you can replace an "HTTP MessageBus implementation" with a "communication record implementation". This approach allows you to easily change the program's way of work without having to make a lot of modifications to the original program. Need to support a new way of communication at any time, just simply create a new Messgaebus implementation. In the sample code below Message, Message only knows you can transfer yourself through MessageBus. Its concrete implementation will take into account how to get the value of Message.

Note: You can't find a function for getting the Message value. Instead, we let Message completely package its data and believe that it can put themselves on Messagebus:

Public interface message {public string send (Messagebus MB) THROWS BUSEXCEPTION;

Messagebus allows you to add new communication mechanisms in supporting MessageBus; similar to this, Message makes you add new Message types at any time.

HttpMessagebus looks at a specific Messagebus implementation, which passes HTTP POST message:

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.urdecoder; import java.net.urlencodod; / *** httpMessageBus is a MessageBus implementation, * it uses HTTP POST to send messages. * @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 (}) {Throw new httpbusexception (Exception.getMessage ());}} private string _formulatepost (String [] value value) {if ((value == null) {i (value === 0)) { Return "";} stringbuffer sb = new stringbuffer (); string new_pair = ""; for (int i = 0; i

} Private void _write (String post, URLConnection conn) throws IOException {DataOutputStream output = new DataOutputStream (conn.getOutputStream ()); output.writeBytes (post); output.flush (); output.close ();} private String _read (URLConnection conn) throws IOException {BufferedReader input = new BufferedReader (new InputStreamReader (conn.getInputStream ())); String temp_string; StringBuffer sb = new StringBuffer (); while (null = ((temp_string = input.readLine ())! )) {Sb.append (TEMP_STRING);} Input.close (); return sb.tostring ();}} You can study this code yourself. About POST, you can find a lot of introductions in the Java TIP column of the Java World website. Here I would like to emphasize that behind a simple MessageBus interface, hide a lot of details. HttpMessageBus is just a URL simply in the configuration; all values ​​transmitted to the sendMessage () are sent to that URL. Any details other than this are hidden after the interface.

AbstractMessage has written several Message implementations will find that Send () can decompose into two basic steps:

1. Convert the internal data of Message to a two-dimensional array.

2. Send array values ​​on MessageBus. This is implemented by calling MessageBus's sendMessage () and transmitted to its two-dimensional array parameters.

Write a new Message implementation each time you have to write a similar Send ().

If you can properly use an abstract class, you will be able to easily write new Message implementations and eliminate redundant code. Take a look at the definition of this AbstractMessage:

Public Abstract Class AbstractMessage Implements Message {

Public String Send (Messagebus MB) throws busException {string [] [] value = value (); string response = mb.sendMessage (VALUES); RETECTED ABST STRING [] [] value ();

As can be seen from the above, AbstractMessage provides a default implementation for Send (). This default implementation brings three benefits:

· You don't have to write the same code over and over again. Instead, there is now a default implementation that can complete the two basic operations defined in front.

· Now, you can write a new Message with only the implementation of providing a values ​​(). In this way, subclasses only need to know how to expand themselves as "key / value pair" arrays. Subclasses don't have to care about how to transfer yourself on the line. The movement of the transfer is the same for any Message. An important use of inheritance is that it can be used in the case of programming by Difference. Determine the subclass and its parent class is also different depending on the difference. For example, Message, the difference between it and the parent class is only different from the data contained, and the way to transmit on the line is the same. With abstract classes, we can use inheritance clean and clear.

· AbstractMessage actually defines a specification that follows this specification when defining new Message. In this way, programmers can clearly know which functions need to be re-implemented when establishing subclasses. Although it is very simple, this programming method makes things easier when derived complex subclasses.

As a class is getting bigger, the above three points will be more obvious.

The Message example assumes that there is a website to provide stock market service. If you want to find a stock message, you will send a POST command to a URL. In addition to the URL, attach the name of the stock code.

The "key / value pair" of the stock code looks like this:

Ticker = BVSN

The Ticker here is "key", BVSN is "value". The key tells the recipient, and the value BVSN is an stock code.

If you want to view the stock market in Yahoo, you have to send such a URL:

Http://finance.yahoo.com/q

And two pairs / value:

· S - Stock Code · D - View Level (Basic Information, Details, etc.)

So, you want to view BVSN, you need the message below:

Http://finance.yahoo.com/q?s=bvsn&d=v1

Similarly, if it is Quicken's stock market system, you have to send such a URL:

http://www.quicken.com/investments/quotes/

And a pair of keys:

Symbol - stock code

So, in Quicken, check BVSN, you need the message below:

http://www.quicken.com/investments/quotes/?symbol=bvsn

The following code is for the implementation of these two Message:

Public class yahoostockquote extends abstractMessage {

private String _ticker; private final static String _TICKER_KEY = "s"; private final static String _D_VALUE = "v1"; private final static String _D_KEY = "d"; public YahooStockQuote (String ticker) {_ticker = ticker;}

Public void setticker (string ticker) {_ticker = Ticker;} protected string [] [] value () {swriting [] [] value value = {_ticker_key, _ticker}, {_d_key, _d_value}}; return value;}} :

Public class quickenstockquote extends abstractMessage {

Private string _ticker; private final static string _ticker_key = "symbol"; public quickenstock quote (String Ticker) {_ticker = ticker;}

Public void setticker (String Ticker) {_ticker = ticker;} protected string [] [] value () {string [] [] values ​​= {{_ticker_key, _ticker}}; return value;}}};

These Message only know how to handle their data and construct a two-dimensional "key / value) array.

Program example Take a look at the following stock information sample program:

Public class quotegetter {

Public final static void main (string [] args) {if (args.length! = 2) {system.out.println ("incorrect users:"); system.out.println ("java quoteter < Ticker> "); return;} string service = args [0]; string ticker = args [1]; message message = null; messagebus bus = null; if (service.equalsignorecase (" Quicken ")) {bus = new httpMessagebus ("http://www.quickets/inventment/quotes/"); Message = New YahoostockQuote (Ticker);} else // default to yahoo {bus = new httpMessagebus ("http://finance.yahoo.com / Q "); Message = New QuickenStock Qote (Ticker);} tryler (message, bus); system.out.println (response);} catch (exception ignore) { System.out.println ( "Lookup Failed for:" ticker); ignore.printStackTrace ();}} private static String sendMessage (Message message, MessageBus bus) throws BusException {return message.send (bus);}} main first Create a suitable Message and Messagebus, then call sendMessage () to send Message. SendMessage () is an example of programming for interfaces, not for implementation. If sendMessage () is only specifically supporting YahoostockQuote or httpMessagebus, you will say it is programming for implementation.

However, the above SendMessage () is programmed for the interface. So you can pass any implementation of this interface to this function as a parameter, making the function more general.

Summary I have successfully used this procedure in their daily work. With interface, I can seamlessly convert communication mechanisms from HTTP POST into a custom protocol. I can also use the Message interface to easily add new messages in the program. In addition, just write a Message abstract base class, I can easily write new functions and multiplex them in other programs. I hope this detailed example will help deepen the previous discussion on abstract classes and interfaces. In addition, the reader can download the source code accompanying the topic, which includes all the code of the entire message sender and other classes that have not been mentioned in this topic.

-------------------------------------------------- --related resources

· Download this article Source code: http://www.javaworld.com/javaworld/javaqa/03-qa-0831-interface.zip

· Another article related to this article "Abstract classes vs. interfaces" tony sintes (JavaWorld, April 2001): http://www.javaworld.com/javaworld/javaqa/2001-04/03-qa-0420-abstract .html

转载请注明原文地址:https://www.9cbs.com/read-4413.html

New Post(0)