模板模式属于行为型模式
1. 意图
2. 主要解决
3. 何时使用
4. 如何解决
5. 关键代码
6. 应用实例
7. 优点
8. 缺点
9. 使用场景
10. 注意事项
1. 定义一个表示元素的接口
ComputerPart.java
package com.demo.gof;
public interface ComputerPart {
public void accept(ComputerPartVisitor computerPartVisitor);
}
2. 创建扩展了上述类的实体类
Keyboard.java
package com.demo.gof;
public class Keyboard implements ComputerPart {
@Override
public void accept(ComputerPartVisitor computerPartVisitor) {
computerPartVisitor.visit(this);
}
}
Monitor.java
package com.demo.gof;
public class Monitor implements ComputerPart {
@Override
public void accept(ComputerPartVisitor computerPartVisitor) {
computerPartVisitor.visit(this);
}
}
Computer.java
package com.demo.gof;
public class Computer implements ComputerPart {
ComputerPart[] parts;
public Computer(){
parts = new ComputerPart[] {
new Mouse(), new Keyboard(), new Monitor()};
}
@Override
public void accept(ComputerPartVisitor computerPartVisitor) {
for (int i = 0; i < parts.length; i++) {
parts[i].accept(computerPartVisitor);
}
computerPartVisitor.visit(this);
}
}
3. 定义一个表示访问者的接口
ComputerPartVisitor.java
package com.demo.gof;
public interface ComputerPartVisitor {
public void visit(Computer computer);
public void visit(Mouse mouse);
public void visit(Keyboard keyboard);
public void visit(Monitor monitor);
}
4. 创建实现了上述类的实体访问者
ComputerPartDisplayVisitor.java
package com.demo.gof;
public class ComputerPartDisplayVisitor implements ComputerPartVisitor {
@Override
public void visit(Computer computer) {
System.out.println("Displaying Computer.");
}
@Override
public void visit(Mouse mouse) {
System.out.println("Displaying Mouse.");
}
@Override
public void visit(Keyboard keyboard) {
System.out.println("Displaying Keyboard.");
}
@Override
public void visit(Monitor monitor) {
System.out.println("Displaying Monitor.");
}
}
5. 使用 ComputerPartDisplayVisitor 来显示 Computer 的组成部分
VisitorPatternDemo.java
package com.demo.gof;
public class VisitorPatternDemo {
public static void main(String[] args) {
ComputerPart computer = new Computer();
computer.accept(new ComputerPartDisplayVisitor());
}
}
编译运行以上 Java 范例,输出结果如下
$ javac -d . src/main/com.demo/gof/VisitorPatternDemo.java
$ java com.ddkk.demo.VisitorPatternDemo
Displaying Mouse.
Displaying Keyboard.
Displaying Monitor.
Displaying Computer.
更多【java-26-Java访问者模式 ( Visitor Pattern )】相关视频教程:www.yxfzedu.com