设计模式之访问者模式

设计模式 Java About 2,149 words

作用

需要对一个对象结构中的对象进行很多不同操作(这些操作彼此没有关联),同时需要避免让这些操作"污染"这些对象的类。

可以对功能进行统一,可以做报表、UI、拦截器与过滤器,适用于数据结构相对稳定的系统。

原理

pic.png

Visitor:抽象访问者,为该对象结构中的ConcreteElement的每一个类声明一个visit操作。

ConcreteVisitor:具体的访问者,实现每个有Visitor声明的操作,是每个操作实现的部分。

ObjectStructure:枚举它的元素,可以提供一个高层的接口,用来允许访问者访问元素。

Element:定义一个accept方法,接收一个访问者对象。

ConcreteElement:具体元素,实现了accept方法。

案例

Vistor抽象访问者

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(" 女人给的评价该歌手很成功 !");
    }
}

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 interface Person {

    void accept(Action action);

}

ConcreteElement具体元素

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

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

ObjectStructure展示元素

public class ObjectStructure {

    private List<Person> people = new ArrayList<>();

    public void attach(Person person) {
        people.add(person);
    }

    public void detach(Person person) {
        people.remove(person);
    }

    public void display(Action action) {
        for (Person person : people) {
            person.accept(action);
        }
    }

}

调用

public class Client {

    public static void main(String[] args) {
        ObjectStructure os = new ObjectStructure();
        os.attach(new Man());
        os.attach(new Woman());
        Success success = new Success();
        os.display(success);
        System.out.println("-------");
        Fail fail = new Fail();
        os.display(fail);
    }

}
Views: 2,771 · Posted: 2019-12-26

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh