设计模式之访问者模式-示例代码

时间:2024-03-07 12:13:57
public interface Element {
    void accept(Visitor visitor);
}
public class FolderElement implements Element {
    private String name;

    public FolderElement(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    @Override
    public void accept(Visitor visitor) {
        visitor.visit(this);
    }
}
public class FileElement implements Element {
    private String name;

    public FileElement(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    @Override
    public void accept(Visitor visitor) {
        visitor.visit(this);
    }
}

一般有几种元素就有几个visit方法

public interface Visitor {
    void visit(FileElement fileElement);

    void visit(FolderElement folderElement);
}
public class FileNameVisitor implements Visitor {
    @Override
    public void visit(FileElement file) {
        System.out.println("File: " + file.getName());
    }

    @Override
    public void visit(FolderElement folder) {
        System.out.println("Folder: " + folder.getName());
    }
}
public class Client {
    public static void main(String[] args) {
        Element folder = new FolderElement("code2024");
        Element file = new FileElement("hello.java");

        // 构建对象结构
        FileSystemStructure fileSystem = new FileSystemStructure(folder,file);

        // 创建访问者
        Visitor fileVisitor = new FileNameVisitor();

        // 对象结构接受访问者访问
        fileSystem.accept(fileVisitor);
    }
}
Folder: code2024
File: hello.java