8.3 The Domain Model
In keeping with the principles
in the book, the foundation of the
application is the transparent domain model in Figure 8-3. The domain model contains the business
relationships of objects that represent the real world. Pet Store is
made up of carts and orders that contain items.
Figure 8-3. The center of an application is the domain model
shopping cart containing cart items, which feeds an order containing
line items. Items consist of products organized into categories. Each
object is a transparent business object implemented as a Java bean
with some properties and some business methods. Example 8-2 shows a CartItem.
I've eliminated the imports and package detail, for
brevity.
Example 8-2. CartItem.java
[1] public class CartItem implements Serializable {Here's what the annotations mean:[1] The Spring framework does not force components to inherit
/*Private Fields*/
private Item item;
private int quantity;
private boolean inStock;
/*JavaBeans Properties*/
[2] public boolean isInStock() { return inStock; }
public void setInStock(boolean inStock) { this.inStock = inStock; }
public Item getItem( ) { return item; }
public void setItem(Item item) {
this.item = item;
}
public int getQuantity( ) { return quantity; }
public void setQuantity(int quantity) {
this.quantity = quantity;
}
[3] public double getTotalPrice() {
if (item != null) {
return item.getListPrice( ) * quantity;
}
else {
return 0;
}
}
/*Public methods*/
public void incrementQuantity( ) {
quantity++;
}
}
from a Spring class. They are fully transparent, and can live outside
of the container for testing purposes, or if Spring would some day
prove inadequate.
[2] Each field is wrapped with get and set methods, so that
Spring can configure them through Java reflection. (Spring can
alternatively configure them through constructors.)
[3] Unlike many EJB applications, it's often
helpful to include business domain logic within the domain model.
I call this model passive. It's
invoked entirely by objects outside of its domain and has coupling
only to other objects within the domain. Notice that it is not merely
a value object, although it does have private properties and public
fields It has business methods to calculate the total price and
increment the quantity. This design makes this business object easy
to understand and reuse, even though the overall design may evolve.
As we
move into persistence,
you'll see other parts of the model as well.