In an UML class diagram, an association is a stronger relationship than a dependency,
association and dependency can be implemented as follows:
Association --> A has-a B object (as a member variable)
public class A {
private B b;
A(B b){
this.b= b;
}
public void myMethod() {
b.callMethod();
}
}
Dependency --> A references B (as a method parameter or return type)
public class A {
public void myMethod(B b) {
b.callMethod();
}
}
In the above example calling b.callMethod()
can be achieve using either association or dependency
I want to know when to use one of the approaches:
p.s - Any example would be more than welcome :)
You model an association only of you intend to introduce an owned property in either of the connected classes. If that is not the case and you only reference the other class in a parameter or so you will use a dependency. In the course of the modeling process you start with usually a simple association or a dependency ad hoc. This is because you feel the binding force between both. A plain (eventually directed) association is the first indication for the property. In a later design stage you will name the role and add multiplicity (thereby removing the direction arrow since the direction is now clarified by the role name usage). Finally you place the dot to show that the role name should be implemented as owned property. Dependencies are more an optional thing like "also look here". It just helps to navigate to the right position but you will not create any property for it.