简介
分离对象数据结构与行为
实例
访问接口
public interface Visitor {
public void visit(Subject sub);
}
访问实现类
public class MyVisitor implements Visitor {
@Override
public void visit(Subject sub) {
System.out.println("visit the subject:"+sub.getSubject());
}
}
Subject类,accept方法,接受将要访问它的对象,getSubject()获取将要被访问的属性,
public interface Subject {
public void accept(Visitor visitor);
public String getSubject();
}
public class MySubject implements Subject {
@Override
public void accept(Visitor visitor) {
visitor.visit(this);
}
@Override
public String getSubject() {
return "love";
}
}
测试:
public class Test {
public static void main(String[] args) {
Visitor visitor = new MyVisitor();
Subject sub = new MySubject();
sub.accept(visitor);
}
}
其他设计模式http://blog.csdn.net/qq_23370223/article/category/7193147