(Java) Composite Pattern AND Visitor Pattern or only Visitor Pattern in use here?

714 views Asked by At

Sorry if this question has been asked before. I could not find a question that addressed EXACTLY this situation I'm in. The closest I've come to finding a satisfactory answer is someone mentioning that a Visitor pattern and Composite pattern can be used together.

My question is this. Say you have a filesystem, consisting of a root directory containing files and other directories with more files and more directories. This follows the Composite pattern, no? Well say I were to design a fileSystemVisitor interface with different Visitor classes and use them to go through the directories and files. Would my design be a combination of the two then? I have as a matter of fact already written the code a while back. It works just fine, but my question is about wether my code uses both patterns or just the one visitor. Below is the code of the DirectoryNode class which (obviously) is for directories. I'm not asking if the code is correct, simply if it follows the aggregation part of the composite pattern.

import java.util.*;

public class DirectoryNode implements FileSystemNode, Iterable<FileSystemNode> {
    private String name;
    private List<FileSystemNode> nodes;

    public DirectoryNode(String name, List<FileSystemNode> nodes) {
        this.name = name;
        this.nodes = nodes;
    }

    public String getName() {
        return name;
    }

    public Iterator<FileSystemNode> iterator() {
        return nodes.iterator();
    }

    public <T> T accept(FileSystemVisitor<T> v) {
        return v.visitDirectory(this);
    }
}

Am I correct to assume that I'm aggregating over FileSystemNode in this class?

Would this UML diagram be correct? or would it be without the aggregation arrow? Composite+Visitor UML

0

There are 0 answers