Developing Java Beans 4.2 Indexed Properties So far we have been talking about properties that have only one value. For each named property, we have a single associated value. But this is not always the best way to represent properties; sometimes a property is better modeled as having multiple values. You can create properties that are actually an ordered collection of values associated with a single name. The individual values are accessed using an integer index, much the same way you would with an array. There is an additional design pattern for indexed properties. The in the standard property method design pattern may be an array, as follows: public [] get(); public void set([] value); These methods are used to access the entire array of property values at one time. An additional method can be used to provide access to individual values in the property array. The method signatures for this pattern are: public get(int index); public void set(int index, value); As with the single value pattern, these methods are allowed to include a throws clause for throwing checked exceptions. Specifically, the indexed methods may throw a java.lang.ArrayIndexOutOfBoundsException if an index is used that is outside the bounds of the property array. Although this is an important aspect of indexed properties, it isn’t required for the indexed properties pattern. Since the indexed properties are considered ordered collections, I think the indexed get() and set() methods should always declare the ArrayIndexOutOfBoundsException. It might have been better to make it a requirement for this pattern. Imagine that we are building a system that tracks stock prices in real time. First, let’s think about building a watch list object that keeps track of prices for a set of stocks. We’ll call this class a WatchList. We then define a property of the WatchList called Stocks which contains a list of stocks for which prices are being tracked. The type of the Stocks property is a String array, and each individual stock is represented by a String. We also implement a read-only property called StockCount that returns the number of stocks in the WatchList. The code looks like this: import java.util.*; public class WatchList { // a vector that contains the actual stock names protected Vector stocks = new Vector(); // constructor public WatchList() { } // the get method for the StockCount property public synchronized int getStockCount() { // the StockCount property is derived from the size of the // stocks Vector return stocks.size(); } page 53
This entry was posted
on Friday, September 29th, 2006 at 3:27 pm and is filed under java.
You can follow any responses to this entry through the RSS 2.0 feed.
Responses are currently closed, but you can trackback from your own site.