added composite example
This commit is contained in:
parent
fa5b8bf520
commit
927a2232dd
5
src/learn/simple_composite/Component.java
Normal file
5
src/learn/simple_composite/Component.java
Normal file
@ -0,0 +1,5 @@
|
||||
package learn.simple_composite;
|
||||
|
||||
public interface Component {
|
||||
void operation();
|
||||
}
|
27
src/learn/simple_composite/Composite.java
Normal file
27
src/learn/simple_composite/Composite.java
Normal file
@ -0,0 +1,27 @@
|
||||
package learn.simple_composite;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class Composite implements Component {
|
||||
private List<Component> children = new ArrayList<>();
|
||||
|
||||
@Override
|
||||
public void operation() {
|
||||
for (Component component : children) {
|
||||
component.operation();
|
||||
}
|
||||
}
|
||||
|
||||
public void add(Component component) {
|
||||
children.add(component);
|
||||
}
|
||||
|
||||
public void remove(Component component) {
|
||||
children.remove(component);
|
||||
}
|
||||
|
||||
public Component getChild(int index) {
|
||||
return children.get(index);
|
||||
}
|
||||
}
|
8
src/learn/simple_composite/Leaf.java
Normal file
8
src/learn/simple_composite/Leaf.java
Normal file
@ -0,0 +1,8 @@
|
||||
package learn.simple_composite;
|
||||
|
||||
public class Leaf implements Component {
|
||||
@Override
|
||||
public void operation() {
|
||||
System.out.println("Leaf operation" + this);
|
||||
}
|
||||
}
|
18
src/learn/simple_composite/Main.java
Normal file
18
src/learn/simple_composite/Main.java
Normal file
@ -0,0 +1,18 @@
|
||||
package learn.simple_composite;
|
||||
|
||||
public class Main {
|
||||
public static void main(String[] args) {
|
||||
Composite root = new Composite();
|
||||
Composite node1 = new Composite();
|
||||
Composite node2 = new Composite();
|
||||
Leaf l1 = new Leaf();
|
||||
Leaf l2 = new Leaf();
|
||||
|
||||
root.add(node1);
|
||||
node1.add(node2);
|
||||
node2.add(l1);
|
||||
node2.add(l2);
|
||||
|
||||
root.operation();
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user