【设计模式】访问者模式
使用频率:★☆☆☆☆
一、什么是访问者模式
在不修改已有程序结构的前提下,通过添加额外的“访问者”来完成对已有代码功能的提升;//定义参考链接
二、补充说明
数据结构的每一部分对象可以接收访问者的调用,该部分对象向访问者传入自身对象,访问者反过来执行该部分对象的相关操作;//有点难理解,看代码吧~
三、角色
抽象访问者
具体访问者
抽象元素
具体元素
对象结构:能枚举它的内部元素,允许访问者访问它的元素
客户端
四、例子,JAVA代码
参考维基百科例子,链接地址,稍微修改了下
例子说明:车为对象结构角色,里面包含轮子,车身等部分对象,访问者角色对象为PrintVisitor,车接受该访问者让其访问车的各个组成对象并打印信息;
抽象访问者
package com.pichen.dp.behavioralpattern.visitor; public interface Visitor { void visit(Wheel wheel); void visit(Engine engine); void visit(Body body); void visit(Car car); }
具体访问者
package com.pichen.dp.behavioralpattern.visitor; public class PrintVisitor implements Visitor { public void visit(Wheel wheel) { System.out.println("Visiting " + wheel.getName() + " wheel"); } public void visit(Engine engine) { System.out.println("Visiting engine"); } public void visit(Body body) { System.out.println("Visiting body"); } public void visit(Car car) { System.out.println("Visiting car"); } }
抽象元素
package com.pichen.dp.behavioralpattern.visitor; public interface Visitable { public void accept(Visitor visitor); }
具体元素,车身,引擎,车轮。。。
package com.pichen.dp.behavioralpattern.visitor; public class Body implements Visitable { @Override public void accept(Visitor visitor) { visitor.visit(this); } }
package com.pichen.dp.behavioralpattern.visitor; public class Engine implements Visitable{ @Override public void accept(Visitor visitor) { visitor.visit(this); } }
package com.pichen.dp.behavioralpattern.visitor; public class Wheel implements Visitable{ private String name; Wheel(String name) { this.name = name; } String getName() { return this.name; } @Override public void accept(Visitor visitor) { visitor.visit(this); } }
对象结构
package com.pichen.dp.behavioralpattern.visitor; public class Car implements Visitable{ private Engine engine = new Engine(); private Body body = new Body(); private Wheel[] wheels = { new Wheel("front left"), new Wheel("front right"), new Wheel("back left"), new Wheel("back right") }; @Override public void accept(Visitor visitor) { visitor.visit(this); engine.accept(visitor); body.accept(visitor); for (int i = 0; i < wheels.length; ++i) wheels[i].accept(visitor); } }
客户端Main
package com.pichen.dp.behavioralpattern.visitor; public class Main { static public void main(String[] args) { Car car = new Car(); Visitor visitor = new PrintVisitor(); car.accept(visitor); } }
结果打印,成功访问到car内部各个元素
Visiting car
Visiting engine
Visiting body
Visiting front left wheel
Visiting front right wheel
Visiting back left wheel
Visiting back right wheel