访问者模式

访问者模式

结果抽象类

abstract class Action{
    public abstract void getManResult(Man man);
    public abstract void getManResult(Woman woman);
}

结果的实现类

class Success extends Action{

    @Override
    public void getManResult(Man man) {
        System.out.println("男人的评价是成功");
    }

    @Override
    public void getManResult(Woman woman) {
        System.out.println("女人的评价是成功");
    }
}
class Fail extends Action{

    @Override
    public void getManResult(Man man) {
        System.out.println("男人给的评价是失败");
    }

    @Override
    public void getManResult(Woman woman) {
        System.out.println("女人的评价是失败");
    }
}

Person抽象类

abstract class Person{
    public abstract void accept(Action action);
}

Person实现类

class Man extends Person{

    @Override
    public void accept(Action action) {
        action.getManResult(this);
    }
}
class Woman extends Person{

    @Override
    public void accept(Action action) {
        action.getManResult(this);
    }
}

管理类

class ObjectStructure{
    private List<Person> persons = new LinkedList<>();
    public void attache(Person person){
        persons.add(person);
    }
    public void detach(Person person){
        persons.remove(person);
    }
    public void display(Action action){
        for (Person p:persons){
            p.accept(action);
        }
    }
}

测试类

public class VisitorTest {
    public static void main(String[] args) {
        ObjectStructure objectStructure = new ObjectStructure();
        objectStructure.attache(new Man());
        objectStructure.attache(new Woman());
        Success success = new Success();
        objectStructure.display(success);//男人女人都是成功
        Fail fail = new Fail();
        objectStructure.display(fail);//男人女人都是失败
    }
}

你可能感兴趣的:(设计模式)