diff --git a/src/learn/simple_composite/Component.java b/src/learn/simple_composite/Component.java new file mode 100644 index 0000000..435c09f --- /dev/null +++ b/src/learn/simple_composite/Component.java @@ -0,0 +1,5 @@ +package learn.simple_composite; + +public interface Component { + void operation(); +} diff --git a/src/learn/simple_composite/Composite.java b/src/learn/simple_composite/Composite.java new file mode 100644 index 0000000..15ee866 --- /dev/null +++ b/src/learn/simple_composite/Composite.java @@ -0,0 +1,27 @@ +package learn.simple_composite; + +import java.util.ArrayList; +import java.util.List; + +public class Composite implements Component { + private List 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); + } +} diff --git a/src/learn/simple_composite/Leaf.java b/src/learn/simple_composite/Leaf.java new file mode 100644 index 0000000..b68f80a --- /dev/null +++ b/src/learn/simple_composite/Leaf.java @@ -0,0 +1,8 @@ +package learn.simple_composite; + +public class Leaf implements Component { + @Override + public void operation() { + System.out.println("Leaf operation" + this); + } +} diff --git a/src/learn/simple_composite/Main.java b/src/learn/simple_composite/Main.java new file mode 100644 index 0000000..c189297 --- /dev/null +++ b/src/learn/simple_composite/Main.java @@ -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(); + } +}