Java Reference
In-Depth Information
Sidebar 5.1 Aggregate association
Aggregation can be implemented as a normal one-to-one association, using
attributes of the container that represent the links to the components. The seman-
tics of aggregation require the lifetime of the components to be bound by the life-
time of the container; when the container is created the components are also
created. There are two main solutions:
initialization in the constructor; and
inline initialization.
The first solution can be written as follows:
bus # new Bus();
This technique has a couple of drawbacks. First, it is error prone: it is easy to
forget to write the creation instructions, resulting in uninitialized attributes.
Second, it is not readable: when looking at the attributes it is impossible to under-
stand that they represent aggregation without looking at the constructor too. The
second alternative, the inline initialization can be implemented as follows:
public Bus bus # new Bus();
This approach overcomes the drawbacks of the previous one. It is less error
prone: it is difficult to forget to create the objects because they are created in the
same place as where they are defined. It is more readable: the final keyword
together with the inline initialization clearly states that these objects are created
once and their lifetime is linked to the lifetime of the compound object.
public final Bus bus # new Bus();
With the above declaration the bus attribute will refer to the same object for all
its lifetime.
The bus is made up of three attributes holding persistently the infor-
mation that components communicate to each other. These attributes are
accessible through getter and setter methods.
public class Bus {
private String data; // the data bus
private String command; // the command bus
private int address; // the address bus
// getter and setter for data bus
public void setData(String data) { this .data # data; }
public String getData() { return data; }
// getter and setter for command bus
public void setCommand(String command)
{ this .command # command; }
public String getCommand() { return command; }
// getter and setter for address bus
public void setAddress( int address)
{ this .address # address; }
public int getAddress() { return address; }
Search WWH ::

Custom Search