JustNote
  • Introduction
  • DesignPattern
    • 七大原则
      • 开闭原则(OCP)
      • 依赖倒置原则(DIP)
      • 单一职责原则(SRP)
      • 接口隔离原则(ISP)
      • 迪米特法则(LoD)
      • 里氏代换原则(LSP)
      • 合成复用原则(CRP)
    • 创建型模式
      • 简单工厂模式
      • 工厂方法模式
      • 抽象工厂模式
      • 建造者模式
      • 单例模式
      • 原型模式
    • 结构型模式
      • 外观模式
      • 装饰模式
      • 适配器模式
      • 享元模式
      • 组合模式
      • 桥接模式
      • 代理模式
    • 行为型模式
      • 模板方法模式
      • 迭代器模式
      • 策略模式
      • 解释器模式
      • 观察者模式
      • 备忘录模式
      • 命令模式
      • 中介者模式
      • 责任链模式
      • 访问者模式
      • 状态模式
  • Java
    • Java Core
      • JVM 如何加载类
      • JVM 垃圾回收
      • JVM G1GC
      • JVM G1GC Q&A
      • JVM 与 Hbase
      • JVM ZGC Overview
      • JVM ZGC 内存管理
      • JVM ZGC 线程
      • JVM ZGC 垃圾回收
      • JVM ZGC 日志分析
      • JVM ZGC 参数调优
    • checkstyle
  • Golang
    • 源码阅读
      • Goroutines
      • Channel
    • gRPC
      • 1、快速开始
      • 2、什么是gRPC
      • 3、gRPC概念梳理
      • 4、基于Golang的gRPC入门
      • 5、gRPC组件ProtocolBuffers介绍
      • 6、gRPC组件Http 2.0
      • 7、错误处理和Debug
      • 8、gRPC身份验证
      • 9、服务注册与发现
      • 10、gRPC与gRPC Gateway
      • 11、gRPC与分布式链路追踪
  • Scala
    • 数据结构与算法
      • 数组
      • 队列
    • 函数式编程
      • 高阶函数
      • 偏函数
    • Immutable Collection
      • List
    • Mutable Collection
      • Array
    • 常见函数操作
      • A
        • aggregate
        • andThen
        • appended
        • appendedAll
      • C
        • chain
        • collect
        • collectFirst
        • combinations
        • compose
        • concat
        • cond
        • condOpt
        • const
        • contains
        • containsSlice
        • copyToArray
        • corresponds
        • count
        • curried
      • D
        • diff
        • distinct
        • distinctBy
        • drop
        • dropRight
        • dropWhile
      • E
        • empty(PartialFunction)
        • empty(collections)
        • endsWith
        • exists
      • F
        • fill
        • filter
        • filterKeys
        • filterNot
        • find
        • findLast
        • flatMap
        • flatten
        • fold
        • foldLeft
        • foldRight
        • forall
        • foreach
        • fromFunction
      • G
        • getOrElse (Map)
        • getOrElse (Option)
        • groupBy
        • groupMap
        • groupMapReduce
        • grouped
      • H
        • head
        • headOption
      • I
        • indexOf
        • indexOfSlice
        • indexWhere
        • indices
        • init
        • inits
        • intersect
        • isDefinedAt (Map)
        • isDefinedAt (Seq)
        • isEmpty
        • isTraversableAgain
      • K
        • keys
      • L
        • last
        • lastIndexOf
        • lastIndexOfSlice
        • lastIndexWhere
        • lastOption
        • length
        • lift
      • M
        • map
        • mapConserve
        • mapValues
        • max
        • maxBy
        • maxByOption
        • maxOption
        • min
        • minBy
        • minByOption
        • minOption
        • mkString
      • N
        • nonEmpty
      • O
        • orElse
      • P
        • padTo
        • par
        • partition
        • partitionMap
        • patch
        • permutations
        • prefixLength
        • prepended
        • prependedAll
        • product
      • R
        • range
        • reduce
        • reduceLeft
        • reduceLeftOption
        • reduceOption
        • reduceRight
        • reduceRightOption
        • reverse
        • reverseIterator
        • reverseMap
        • runWith
      • S
        • sameElements
        • scan
        • scanLeft
        • scanRight
        • search
        • segmentLength
        • size
        • slice
        • sliding
        • sortBy
        • sortWith
        • sorted
        • span
        • splitAt
        • startsWith
        • sum
      • T
        • tabulate
        • tail
        • tails
        • take
        • takeRight
        • takeWhile
        • transpose
        • tupled
      • U
        • unfold
        • union
        • unlift
        • untupled
        • unzip
        • unzip3
        • updated
      • V
        • values
        • view
      • W
        • withFilter
        • withDefault
        • withDefaultValue
      • Z
        • zip
        • zipAll
        • zipWithIndex
      • map
      • flatmap
      • filter
      • reduceLeft
      • foldLeft
    • Futures
      • Method with future as return type
      • Non blocking future result
      • Chain futures using flatMap
      • Chain futures using for comprehension
      • Future Option with for comprehension
      • Future Option with map
      • Composing Futures
      • Future Sequence
      • Future Traverse
      • Future foldLeft
      • Future reduceLeft
      • Future firstCompletedOf
      • Future zip
      • Future zipWith
      • Future andThen
      • Future configure threadpool
      • Future recover
      • Future recoverWith
      • Future fallbackTo
      • Future promise
    • Akka
  • Algorithm
  • Docker
  • Kubernetes
    • 二进制安装kubernetes
      • 00.从零开始
  • Architecture
    • Infrastructure
      • Opentracing
      • Jaeger && ZipKin
      • SkyWalking
      • Consul
      • Envoy
      • Service Mesh
      • Service Mesh: Istio 详解
      • Service Mesh: 基于 Istio 的落地实践(一)
    • CAS
      • CAS Server
      • CAS Service Management
      • CAS 集成LDAP
      • CAS 集成gitlab
      • CAS SSO & SLO
      • CAS Gitbook
    • xCAT
  • Netty
  • DDD
  • Reactive Programming
    • Reactor
      • Publisher
      • Subscriber
      • Subscription
      • Processor
    • WebFlux
  • Gitlab
    • Git Hook
  • CICD
    • Jenkins
      • Kubectl
Powered by GitBook
On this page
  • 适用场景
  • 优点
  • 缺点
  • Golang Demo
  • Java Demo
  • UML
  • 补充另一个版本的Java/Scala Demo 以及源码解析
  • Java Demo_
  • Scala Demo
  • UML_
  • 源码解析

Was this helpful?

  1. DesignPattern
  2. 行为型模式

访问者模式

访问者模式(Visitor Pattern):提供一个作用于某对象结构中的各元素的操作表示,它使我们可以在不改变各元素的类的前提下定义作用于这些元素的新操作。

封装用于某数据结构(List、Set、Map)中各种元素的操作,核心是封装操作。

适用场景

  • 当一个数据结构如(List、Set、Map)包含很多类型对象。

  • 数据结构与数据操作分离

优点

  • 增加新的操作很容易,新增一个访问者就可以

缺点

  • 增加新的数据结构困难

  • 具体元素变更比较麻烦

下面我们引入一个应用场景。在很多视频网站上,会有很多的免费视频,以及付费视频。用户去视频网站浏览的时候,就是一个个访问者。接下来我们通过代码来模拟一下这个业务逻辑。

注意: 在实际工作中,并不一定常用访问者模式。一单要使用访问者模式,就说明,这个应用场景必须要使用访问者模式来解决问题,或者说使用访问者模式能让问题解决地更优雅。

Golang Demo

package visitor

import "fmt"

type IVisitor interface {
    visit(interface{})
}

// 定义一个visitor 实现IVisitor 接口
type Visitor struct {
}

// golang 中不支持重载,所以这里的visit 方法,我们需要费劲一点
func (Visitor) visit(i interface{}) {
    switch i.(type) {
    case FreeVideo:
        video := i.(FreeVideo)
        fmt.Println("Free Video " + video.name)
    case VipVideo:
        video := i.(VipVideo)
        fmt.Printf("Vip Video  %v : Price  %d \n", video.name, video.price)
    }
}

// IVideo 和 Video的组合 模拟一个抽象类
type IVideo interface {
    accept(visitor IVisitor)
}
type Video struct {
    name string
}

type FreeVideo struct {
    Video
}

func (f FreeVideo) accept(visitor IVisitor) {
    visitor.visit(f)
}

type VipVideo struct {
    Video
    price int
}

func (v VipVideo) accept(visitor IVisitor) {
    visitor.visit(v)
}
package visitor

func ExampleVisitor() {

    videoList := []IVideo{}
    freeVideo := FreeVideo{}
    freeVideo.name = "一条狗的使命"

    vipVideo := VipVideo{}
    vipVideo.name = "流浪地球"
    vipVideo.price = 6

    videoList = append(videoList, freeVideo)
    videoList = append(videoList, vipVideo)

    for _, video := range videoList {
        video.accept(Visitor{})
    }

    // Output:
    // Free Video 一条狗的使命
    // Vip Video  流浪地球 : Price  6
}

Java Demo

定义一个访问者的接口

package tech.selinux.design.pattern.behavioral.visitor;

/** 定义了一个访问者的接口 */
public interface IVisitor {
  void visit(FreeVideo freeVideo);

  void visit(VipVideo vipVideo);
}

定义视频的抽象类

package tech.selinux.design.pattern.behavioral.visitor;

public abstract class Video {
  private String name;

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  // 是否接受访问者的访问
  public abstract void accept(IVisitor visitor);
}
package tech.selinux.design.pattern.behavioral.visitor;

/** 定义了一个免费视频 继承了视频类 */
public class FreeVideo extends Video {
  @Override
  public void accept(IVisitor visitor) {
    visitor.visit(this);
  }
}
package tech.selinux.design.pattern.behavioral.visitor;

public class VipVideo extends Video {
  private int price;

  public int getPrice() {
    return price;
  }

  public void setPrice(int price) {
    this.price = price;
  }

  /** 这里会根据传入的类型调用相应的方法 */
  @Override
  public void accept(IVisitor visitor) {
    visitor.visit(this);
  }
}

定义了visitor,visitor会根据传入的视频类别来进行访问。

package tech.selinux.design.pattern.behavioral.visitor;

public class Visitor implements IVisitor {
  @Override
  public void visit(FreeVideo freeVideo) {
    System.out.println("Free Video " + freeVideo.getName());
  }

  @Override
  public void visit(VipVideo vipVideo) {
    System.out.println("Vip Video " + vipVideo.getName() + ": Price " + vipVideo.getPrice());
  }
}
package tech.selinux.design.pattern.behavioral.visitor;

import java.util.ArrayList;
import java.util.List;

public class Test {
  public static void main(String[] args) {
    List<Video> videoList = new ArrayList<Video>();

    FreeVideo freeVideo = new FreeVideo();
    freeVideo.setName("一条狗的使命");

    VipVideo vipVideo = new VipVideo();
    vipVideo.setName("流浪地球");
    vipVideo.setPrice(6);

    videoList.add(freeVideo);
    videoList.add(vipVideo);

    for (Video video : videoList) {
      video.accept(new Visitor());
    }
  }
}

UML

补充另一个版本的Java/Scala Demo 以及源码解析

Java Demo_

Scala Demo

UML_

源码解析

Previous责任链模式Next状态模式

Last updated 5 years ago

Was this helpful?

访问者模式UML