Visitor Pattern
Posted nedrain
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Visitor Pattern相关的知识,希望对你有一定的参考价值。
问题
Solve
// Action.java
public abstract class Action {
public abstract void getManResult(Man man);
public abstract void getWomanResult(Woman woman);
}
// Success.java
public class Success extends Action {
@Override
public void getManResult(Man man) {
System.out.println("Man said you‘re great.");
}
@Override
public void getWomanResult(Woman woman) {
System.out.println("Woman said you are great.");
}
}
// Fail.java
public class Fail extends Action{
@Override
public void getManResult(Man man) {
System.out.println("Man said you are a looser.");
}
@Override
public void getWomanResult(Woman woman) {
System.out.println("Woman said you‘re a looser.");
}
}
// Person.java
public abstract class Person {
public abstract void accept(Action action);
}
// Man.java
public class Man extends Person{
@Override
public void accept(Action action) {
action.getManResult(this);
}
}
//Woman.java
public class Woman extends Person {
@Override
public void accept(Action action) {
action.getWomanResult(this);
}
}
//ObjectStructure.java
import java.util.LinkedList;
import java.util.List;
public class ObjectStructure {
private List<Person> personList = new LinkedList<Person>();
public void attach(Person p){
personList.add(p);
}
public void detach(Person p){
personList.remove(p);
}
public void display(Action action){
for(Person p : personList){
p.accept(action);
}
}
}
以上是关于Visitor Pattern的主要内容,如果未能解决你的问题,请参考以下文章