Experiment Task: Composite Pattern
Implement the "Folder Browisng" Example Using Transparent Composite Patern
1. Class Diagram
(Class diagram omitted)
2. Source Code
public abstract class Node {
private String label = "";
public Node(String label) {
this.label = label;
}
protected String getLabel() {
return label;
}
protected abstract void display(String prefix);
protected void add(Node node) {
throw new UnsupportedOperationException("This object does not support add operation");
}
protected void remove(Node node) {
throw new UnsupportedOperationException("This object does not support remove operation");
}
}
public class LeafNode extends Node {
public LeafNode(String label) {
super(label);
}
@Override
public void display(String prefix) {
System.out.println(prefix + "-" + getLabel());
}
}
import java.util.ArrayList;
import java.util.List;
public class CompositeNode extends Node {
private List<Node> children = new ArrayList<>();
public CompositeNode(String label) {
super(label);
}
@Override
protected void display(String prefix) {
System.out.println(prefix + "+" + getLabel());
if (children != null) {
for (Node child : children) {
child.display(prefix + " ");
}
}
}
@Override
protected void add(Node node) {
children.add(node);
}
@Override
protected void remove(Node node) {
children.remove(node);
}
}
public class Client {
public static void main(String[] args) {
Node rootFolder = new CompositeNode("Clothing");
Node summerClothes = new CompositeNode("Summer Wear");
Node winterClothes = new CompositeNode("Winter Wear");
LeafNode dress = new LeafNode("Dress");
LeafNode vest = new LeafNode("Vest");
LeafNode coat = new LeafNode("Coat");
rootFolder.add(summerClothes);
rootFolder.add(winterClothes);
summerClothes.add(dress);
summerClothes.add(vest);
winterClothes.add(coat);
rootFolder.display("");
}
}
The output will show the folder structure with '+' for folders and '-' for leaf nodes, indented to representt hierarchy.