Designing RMI Applications
import java.rmi.server.*; /* The only difference between this and Account_Impl is that Account_Impl extends UnicastRemote. */ public class Account_Impl2 implements Account { private Money _balance; public Account_Impl2(Money startingBalance) throws RemoteException { _balance = startingBalance; } public Money getBalance() throws RemoteException { return _balance; } public void makeDeposit(Money amount) throws RemoteException, NegativeAmountException { checkForNegativeAmount(amount); _balance.add(amount); return; } public void makeWithdrawal(Money amount) throws RemoteException, OverdraftException, NegativeAmountException { checkForNegativeAmount(amount); checkForOverdraft(amount); _balance.subtract(amount); return; } /** We must define this function */ public boolean equals(Object object) { // three cases. Either it's us, or it's our stub, or it's // not equal. if (object instanceof Account_Impl2) { return (object == this); } if (object instanceof RemoteStub) { try { RemoteStub ourStub = (RemoteStub) RemoteObject.toStub(this); return ourStub.equals(object); } catch (NoSuchObjectException e) { // we're not listening on a port, therefore it's not our // stub } } return false; } /** We must define this function */ public int hashCode() { try { Remote ourStub = RemoteObject.toStub(this); return ourStub.hashCode(); } catch (NoSuchObjectException e) { } return super.hashCode(); } private void checkForNegativeAmount(Money amount) throws NegativeAmountException { int cents = amount.getCents(); if (0 > cents) { throw new NegativeAmountException(); } } private void checkForOverdraft(Money amount) throws OverdraftException { if (amount.greaterThan(_balance)) { throw new OverdraftException(false); } return; } }
exportObject
after creating one of
these.equals()
and
hashCode()
. These are tricky to implement. The code
here gets around that by creating a stub of itself and letting
that stub to the work.UnicastRemoteObject
,
you can use a tie
server.UnicastRemoteObject
and implements the remote interface. The implementation, however,
simply forwards all method calls to the real server (cf. Adapter
pattern).23 of 49