表示一个作用于某对象结构中的各元素的操作。它使你可以在不改变各元素的类的前提下定义作用于这些元素的新操作
public abstract class Action { /** * 男人的结论 * * @param man */ public abstract void manConclusion(Man man); /** * 女人的结论 * * @param woman */ public abstract void womanConclusion(Woman woman); }
public class Success extends Action { @Override public void manConclusion(Man man) { System.out.println("背后有个强大的女人!"); } @Override public void womanConclusion(Woman woman) { System.out.println("个人素质优秀!"); } }
public abstract class People { /** * 男女态度 * * @param visitor */ public abstract void accept(Action visitor); }
public class Man extends People { @Override public void accept(Action visitor) { visitor.manConclusion(this); } }
public class Woman extends People { @Override public void accept(Action visitor) { visitor.womanConclusion(this); } }
public class ObjectStructure { private final ListpeopleList = new ArrayList<>(); /** * 添加 * * @param people */ public void add(People people) { peopleList.add(people); } /** * 删除 * * @param people */ public void remove(People people) { peopleList.remove(people); } /** * 结果展示 */ public void display(Action visitor) { for (People p : peopleList) { p.accept(visitor); } } }
public class Main { public static void main(String[] args) { ObjectStructure objectStructure = new ObjectStructure(); objectStructure.add(new Woman()); objectStructure.add(new Man()); Success success = new Success(); objectStructure.display(success); } }
优点
缺点