Java 设计模式 之 访问者模式
http://www.verejava.com/?id=16999202350980
package com.visit.theory;
import java.util.ArrayList;
public class Test
{
public static void main(String[] args)
{
ObjectStructure o = new ObjectStructure(); //依赖于ObjectStructure
//实例化具体元素
o.attach(new Man());
o.attach(new Woman());
//当成功时不同元素的不同反映
Visitor success = new Success(); //依赖于抽象的Visitor接口
o.display(success);
//当恋爱时的不同反映
Visitor amativeness = new Love(); //依赖于抽象的Visitor接口
o.display(amativeness);
}
}
package com.visit.theory;
public interface Visitor
{
public void visit(Man man);
public void visit(Woman w);
}
package com.visit.theory;
public interface Person
{
void accept(Visitor visitor);
}
package com.visit.theory;
public class Woman implements Person {
// 先对visitor进行类型转换,再执行visit方法,因为Visitor接口已经没有声明任何抽象方法了
public void accept(Visitor visitor) {
visitor.visit(this);
}
}
package com.visit.theory;
public class Man implements Person {
// 先对visitor进行类型转换,再执行visit方法,因为Visitor接口已经没有声明任何抽象方法了
public void accept(Visitor visitor) {
visitor.visit(this);
}
}
package com.visit.theory;
public class Success implements Visitor{
public void visit(Man man) {
System.out.println("当男人成功时,背后多半有一个伟大的女人");
}
public void visit(Woman girl) {
System.out.println("当女人成功时,背后大多有一个不成功的男人");
}
}
package com.visit.theory;
public class Love implements Visitor{
public void visit(Man man) {
System.out.println("当男人恋爱时,凡事不懂也装懂");
}
public void visit(Woman girl) {
System.out.println("当女人恋爱时,遇事懂也装不懂");
}
}
package com.visit.theory;
import java.util.ArrayList;
import java.util.List;
public class ObjectStructure
{
private List<Person> elements = new ArrayList<Person>();
public void attach(Person element){
elements.add(element);
}
public void detach(Person element){
elements.remove(elements);
}
//遍历各种具体元素并执行他们的accept方法
public void display(Visitor visitor){
for(Person p:elements){
p.accept(visitor);
}
}
}