added composite example

This commit is contained in:
Louis Heredero 2024-11-18 10:52:39 +01:00
parent fa5b8bf520
commit 927a2232dd
Signed by: HEL
GPG Key ID: 8D83DE470F8544E7
4 changed files with 58 additions and 0 deletions

View File

@ -0,0 +1,5 @@
package learn.simple_composite;
public interface Component {
void operation();
}

View 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);
}
}

View File

@ -0,0 +1,8 @@
package learn.simple_composite;
public class Leaf implements Component {
@Override
public void operation() {
System.out.println("Leaf operation" + this);
}
}

View 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();
}
}