Class StampDispenser
illustrates
the basic form of a service-oriented object. Its instance variables
are private, so its accessible methods are the only way to manipulate
the state of the object. Although service-oriented objects like StampDispenser
have
state, they use their state to decide how to behave when their methods
are invoked. Consider the code of StampDispenser
's
add
method, shown in
Listing 6-1. The add
method of StampDispenser
package com.artima.examples.stampdispenser.ex1; //... public class StampDispenser { private final static int STAMP_VALUE = 20; private int balance; //... public synchronized void add(int amount) { if ((amount != 5) && (amount != 10)) { throw new IllegalArgumentException(); } balance += amount; if (balance >= STAMP_VALUE) { // Dispense a stamp and return any change // balance - STAMP_VALUE is amount in excess of twenty cents // (the stamp price) to return as change. After dispensing the // stamp and returning any change, the new balance will be zero. StampDispenserEvent event = new StampDispenserEvent(this, balance - STAMP_VALUE, 0); balance = 0; fireStampDispensed(event, listenersClone); } else { // Fire an event to indicate the balance has increased StampDispenserEvent event = new StampDispenserEvent(this, amount, balance); fireCoinAccepted(event, listenersClone); } } //... }
StampDispenser
's balance
variable
keeps track of the amount of money inserted but not returned or
exchanged for stamps. StampDispenser
offers no data-oriented
methods to set and get the balance
. Rather, it uses
the balance
to decide how to behave when its service-oriented
methods add
and returnCoins
are invoked.
As shown by the highlighted portions of StampDispenser
's add
method is
invoked, it uses its current balance
to decide whether
or not to dispense a stamp, whether or not to return any change,
and what new value to give to balance
.
This guideline's main point is that in the basic, expert object design, objects keep their state private and expose only their behavior. The state can be either mutable or immutable. The reason such objects have state is to help them decide how to behave when called upon to perform a service. Thus, even though such objects have both state and behavior, they are service-oriented, not data-oriented.
|
Last Updated: Sunday, May 11, 2003
Copyright © 1996-2003 Artima Software, Inc. All Rights Reserved. |
URL: http://www.artima.com/objectdesign/object15.html
Artima.com is created by Bill Venners |