将观众分为男人和女人,对歌手进行测评,当看完某个歌手表演后,得到他们对该歌手不同的评价(评价有不同的种类,比如 成功、失败等)。
假设要添加一个 Wait 的状态类,考察 Man 类和 Woman 类的反应,只需增加一个 Action 子类即可在客户端调用即可,不需要改动任何其他类的代码。
// visitor
public abstract class Action {
//得到男性 的测评
public abstract void getManResult(Man man);
//得到女性 的测评
public abstract void getWomanResult(Woman woman);
}
// ConcreteVisitor:评价为成功
public class Success extends Action {
@Override
public void getManResult(Man man) {
System.out.println(" 男人给的评价该歌手很成功 !");
}
@Override
public void getWomanResult(Woman woman) {
System.out.println(" 女人给的评价该歌手很成功 !");
}
}
//ConcreteVisitor:评价为失败
public class Fail extends Action {
@Override
public void getManResult(Man man) {
System.out.println(" 男人给的评价该歌手失败 !");
}
@Override
public void getWomanResult(Woman woman) {
System.out.println(" 女人给的评价该歌手失败 !");
}
}
// Element
public abstract class Person {
//提供一个方法,让访问者可以访问
public abstract void accept(Action action);
}
// ConcreteElement1:男人 使用了双分派
public class Man extends Person {
@Override
public void accept(Action action) {
action.getManResult(this);
}
}
// ConcreteElement2:女人 使用了双分派
public class Woman extends Person{
@Override
public void accept(Action action) {
action.getWomanResult(this);
}
}
//数据结构,管理很多人(Man , Woman)
public class ObjectStructure {
//维护了一个集合
private List<Person> persons = new LinkedList<>();
//增加到list
public void attach(Person p) {
persons.add(p);
}
//移除
public void detach(Person p) {
persons.remove(p);
}
//显示测评情况
public void display(Action action) {
for(Person p: persons) {
p.accept(action);
}
}
}
// 客户端
public class Client {
public static void main(String[] args) {
//创建ObjectStructure
ObjectStructure objectStructure = new ObjectStructure();
objectStructure.attach(new Man());
objectStructure.attach(new Woman());
// 成功
Success success = new Success();
objectStructure.display(success);
// 失败
System.out.println("===============");
Fail fail = new Fail();
objectStructure.display(fail);
}
}
原文:https://www.cnblogs.com/Songzw/p/13089227.html