/** Specialized I/O exception to request some kind of user confirmation.
* A code that needs to ask user shall not attempt to open a dialog itself,
* rather it shall emit this exception and let its callers show the dialog
* at appropriate time.
*/
public abstract class UserQuestionException extends IOException {
/** Description of the dialog to show to the user. Whoever catches
* this exception shall use
* {@link #getQuestionPane()}.
* {@link JOptionPane#createDialog(java.lang.String)}
* to construct and display the dialog.
*
* @return the pane to display to user
*/
public abstract JOptionPane getQuestionPane();
/** When the user confirms (or rejects) message presented by the
* {@link #getQuestionPane()} dialog, the exception shall be notified
* by calling this method with {@link JOptionPane#getValue()} option.
*
* @param option the option selected by the user
*/
public abstract void confirm(Object option);
}
confirm就是我说的setters
接上篇讲异常的扩展性我们可以整出两个版本
V1:
try {
OutputStream os = where.openConnection().getOutputStream();
os.write(what.toString().getBytes());
os.close();
} catch (IOException ex) {
JOptionPane.showMessageDialog(null, ex);
}
和V2
try {
OutputStream os = where.openConnection().getOutputStream();
os.write(what.toString().getBytes());
os.close();
} catch (UserQuestionException ex) {
JOptionPane p = ex.getQuestionPane();
JDialog d = p.createDialog(ex.getLocalizedMessage());
setVisible(d, p);
ex.confirm(p.getValue());
if (
!p.getValue().equals(JOptionPane.CANCEL_OPTION) &&
!p.getValue().equals(JOptionPane.CLOSED_OPTION)
) {
continue;
}
} catch (IOException ex) {
JOptionPane.showMessageDialog(null, ex);
}
最后:
public final class QueryStream extends OutputStream {
private ByteArrayOutputStream arr = new ByteArrayOutputStream();
/** this field can be manipulated by the QueryException */
Boolean reverse;
@Override
public synchronized void write(byte[] b, int off, int len)
throws IOException {
if (reverse == null) {
throw new QueryException();
}
arr.write(b, off, len);
}
@Override
public synchronized void write(int b) throws IOException {
if (reverse == null) {
throw new QueryException();
}
arr.write(b);
}
@Override
public String toString() {
if (reverse == null) {
return "Reverse question was not answered yet!";
}
if (reverse) {
StringBuilder sb = new StringBuilder();
sb.append(arr.toString());
sb.reverse();
return sb.toString();
}
return arr.toString();
}
private class QueryException extends UserQuestionException {
@Override
public JOptionPane getQuestionPane() {
JOptionPane p = new JOptionPane("Store in reverse way?");
p.setOptionType(JOptionPane.YES_NO_CANCEL_OPTION);
return p;
}
@Override
public void confirm(Object option) {
if (option.equals(JOptionPane.YES_OPTION)) {
reverse = Boolean.TRUE;
return;
}
if (option.equals(JOptionPane.NO_OPTION)) {
reverse = Boolean.FALSE;
return;
}
}
}
}