From what i have read about program structure i think this would be an example of aggregation. Im not quite sure so dont quote me on this
but i think it shows an alternate way of coding from using Inheritance.
First lets define aggregation. "Gathered togther into a mass or sum so as to consitute a whole " but i like websters definition better "Any total or whole considered with refrence to it's constitute parts" So how do we represent aggregation into our code? Good question.
I coded a small multithreaded program (note the lack of synchronization) to try and understand aggregation (or at least what i think aggregation is). The code dosent do much, all that is acomplished is two seperate threads of execution, one writing and one reading but notice the constructor signatures of the two classes Counter and Printer and notice the two calls to the constructors in the main method. See how a refrence to the Storage class is being passed in.
This style of coding seems to be an alternative to extending or subclassing a class as far as i can tell.
Code:
class Storage{
int value;
void setValue(int i){value = i;}
int getValue(){return value;}
}
class Printer implements Runnable{
Thread t1;
Storage store;
public Printer(Storage target){
store = target;
t1 = new Thread(this);
t1.start();
}
public void run(){
try{
while(true){
System.out.println("The value of storage is" + store.getValue());
t1.sleep(1000); // 1 second of sleep
}
}catch(Exception e){System.err.println(e);}
}
}
class Counter implements Runnable{
Thread t2;
int i;
Storage storage;
public Counter(Storage target){
storage = target;
t2 = new Thread(this);
t2.start();
}
public void run(){
try{
while(true){
storage.setValue(i);
++i;
t2.sleep(1000); // 1 second of sleep
}
}catch(Exception e){System.err.println(e);}
}
}
public class Client{
public static void main(String[] args){
Storage store = new Storage();
new Counter(store);
new Printer(store);
}
}