Skip to content

Instantly share code, notes, and snippets.

@madsonic
Created September 14, 2017 13:24
Show Gist options
  • Save madsonic/ef5e41740d04e5c8b36ec31e0cf8f280 to your computer and use it in GitHub Desktop.
Save madsonic/ef5e41740d04e5c8b36ec31e0cf8f280 to your computer and use it in GitHub Desktop.
Association, dependency, composition and aggregation
public class Aggregation {
Foo foo;
public Aggregation(Foo foo) {
this.foo = foo;
}
}
public class Composition {
Foo foo;
public Composition(int val) {
foo = new Foo(val);
}
}
import java.util.HashSet;
public class Foo {
int val;
public Foo(int val) {
this.val = val;
}
public void doSomethingUseless() {
// HashSet is a dependency
HashSet<String> set = new HashSet<>();
}
public void doSomethingUselessAgain(HashSet<String> set) {
// HashSet also considered dependency
HashSet<String> aSet = set;
}
}
public class Main {
public static void main(String[] args) {
// Aggregation example
Foo foo1 = new Foo(1);
Foo foo2 = new Foo(2);
Aggregation agg = new Aggregation(foo1);
agg = new Aggregation(foo2);
// foo1 still exists
// Composition example
Composition com = new Composition(10);
com = new Composition(11);
System.out.println(com.foo.val); // prints 11. the previous foo can no longer be referenced
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment