设计模式之访问者模式

访问者模式(Visitor)

定义

表示一个作用于某对象结构中的各元素的操作,它使你可以在不改变各元素类的前提下定义作用于这些元素的新操作。

使用场景

主要角色

  1. 元素(Element)
  2. 具体元素(ConcreteElement)
  3. 访问者(Visitor)
  4. 具体访问者(ConcreteVisitor)
  5. 对象结构(ObjectStructure)

类图

示例代码

java 复制代码
public interface Element {
    void accept(Visitor visitor);
}
java 复制代码
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);
    }
}
java 复制代码
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方法

java 复制代码
public interface Visitor {
    void visit(FileElement fileElement);

    void visit(FolderElement folderElement);
}
java 复制代码
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());
    }
}
java 复制代码
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
相关推荐
willow19 小时前
Axios由浅入深
设计模式·axios
七月丶3 天前
别再手动凑 PR 了:这个 AI Skill 会按仓库习惯自动建分支、拆提交、提 PR
人工智能·设计模式·程序员
刀法如飞3 天前
从程序员到架构师:6大编程范式全解析与实践对比
设计模式·系统架构·编程范式
九狼3 天前
Flutter + Riverpod +MVI 架构下的现代状态管理
设计模式
静水流深_沧海一粟3 天前
04 | 别再写几十个参数的构造函数了——建造者模式
设计模式
StarkCoder3 天前
从UIKit到SwiftUI的迁移感悟:数据驱动的革命
设计模式
阿星AI工作室4 天前
给openclaw龙虾造了间像素办公室!实时看它写代码、摸鱼、修bug、写日报,太可爱了吧!
前端·人工智能·设计模式
_哆啦A梦5 天前
Vibe Coding 全栈专业名词清单|设计模式·基础篇(创建型+结构型核心名词)
前端·设计模式·vibecoding
阿闽ooo8 天前
中介者模式打造多人聊天室系统
c++·设计模式·中介者模式