一、组件
package com.study.visitor
interface IComponent {
fun getPrice(): Float
fun accept(v: IVisitor)
}
package com.study.visitor
class CPU : IComponent {
override fun getPrice(): Float = 90f
override fun accept(v: IVisitor) {
v.visitorCpu(this)
}
}
package com.study.visitor
class Screen : IComponent {
override fun getPrice(): Float = 30f
override fun accept(v: IVisitor) {
v.visitorScreen(this)
}
}
二、访问者
package com.study.visitor
interface IVisitor {
fun visitorCpu(cpu: CPU);
fun visitorScreen(screen: Screen);
}
package com.study.visitor
class CompanyVisitor : IVisitor {
var totalPrice: Float = 0f
override fun visitorCpu(cpu: CPU) {
totalPrice += cpu.getPrice() * 0.9f
}
override fun visitorScreen(screen: Screen) {
totalPrice += screen.getPrice() * 0.8f
}
}
package com.study.visitor
class CompanyVisitor : IVisitor {
var totalPrice: Float = 0f
override fun visitorCpu(cpu: CPU) {
totalPrice += cpu.getPrice() * 0.9f
}
override fun visitorScreen(screen: Screen) {
totalPrice += screen.getPrice() * 0.8f
}
}
三、主程序调用
package com.study.visitor
fun main() {
val cpu = CPU()
val screen = Screen()
val studentVisitor = StudentVisitor()
val companyVisitor = CompanyVisitor()
cpu.accept(studentVisitor)
screen.accept(studentVisitor)
println(studentVisitor.totalPrice)
cpu.accept(companyVisitor)
screen.accept(companyVisitor)
println(companyVisitor.totalPrice)
}