Dependency injection and aggregation/association
In both association and aggregation, one class maintains a reference to another开发者_Go百科 class.
Then, does constructor injection imply composition? Going by the same logic, is it safe to say that setter injection leads to an association, and not an aggregation?
An aggregation is merely another representation of an association. So setter injection leads to an association and aggregation -- as does constructor injection.
It's debatable as to whether constructor injection implies composition since, according to a strict interpretation of composition, the class itself must be responsible for both the construction and destruction of the composite class.
At java code level if you have a class 2 and Class 3 this the expected code.
Traditional association 0..1 to 0..1 gives the following code:
public class Class2 {
private Class3 class3;
public Class3 getClass3() {
return class3;
}
public void setClass3(Class3 class3) {
this.class3 = class3;
}
}
Class 3 is the same code as Class 2.
Please note that association are related to attributes and not to methods therefore if we decide not to use accessors then the code would only be:
public class **Class2** {
private Class3 class3;
Aggregation 1 to many gives the following code:
import java.util.Collection;
import java.util.Iterator;
public class Class2 {
private Collection<Class3> class3 = null;
public Collection<Class3> getClass3() {
return class3;
}
public Iterator<Class3> class3Iterator() {
return class3.iterator();
}
public boolean isClass3Empty() {
return class3.isEmpty();
}
public boolean containsClass3(Class3 class3) {
return this.class3.contains(class3);
}
public boolean containsAllClass3(Collection<Class3> class3) {
return this.class3.containsAll(class3);
}
public int class3Size() {
return class3.size();
}
public Class3[] class3ToArray() {
return class3.toArray(new Class3[class3.size()]);
}
public void setClass3(Collection<Class3> class3) {
this.class3 = class3;
}
public boolean addClass3(Class3 class3) {
return this.class3.add(class3);
}
public boolean removeClass3(Class3 class3) {
return this.class3.remove(class3);
}
public void clearClass3() {
this.class3.clear();
}
}
public class Class3 {
private Class2 class2 = null;
public Class2 getClass2() {
return class2;
}
public void setClass2(Class2 class2) {
this.class2 = class2;
}
}
Hope this helps
精彩评论