Radio

一个小小程序员

0%

访问者模式

访问者模式

在访问者模式(Visitor Pattern)中,我们使用了一个访问者类,它改变了元素类的执行算法。通过这种方式,元素的执行算法可以随着访问者改变而改变。这种类型的设计模式属于行为型模式。根据模式,元素对象已接受访问者对象,这样访问者对象就可以处理元素对象上的操作。

示例演示:
  1. 定义一个people接口和三个动作的实现类

    1
    2
    3
    4
    5
    package test.visitor;

    public interface People {
    void action(PeopleVisitor peopleVisitor);
    }
    1
    2
    3
    4
    5
    6
    7
    8
    package test.visitor;

    public class PeopleAwake implements People{
    @Override
    public void action(PeopleVisitor peopleVisitor) {
    peopleVisitor.visit(this);
    }
    }
    1
    2
    3
    4
    5
    6
    7
    8
    package test.visitor;

    public class PeopleEat implements People{
    @Override
    public void action(PeopleVisitor peopleVisitor) {
    peopleVisitor.visit(this);
    }
    }
    1
    2
    3
    4
    5
    6
    7
    8
    package test.visitor;

    public class PeopleSleep implements People{
    @Override
    public void action(PeopleVisitor peopleVisitor) {
    peopleVisitor.visit(this);
    }
    }
  2. 定义一个访问者接口

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    package test.visitor;

    public interface PeopleVisitor {

    void visit(PeopleAwake peopleAwake);

    void visit(PeopleEat peopleEat);

    void visit(PeopleSleep peopleSleep);
    }
  3. 新建一个实现了访问者接口的访问者实体类

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    package test.visitor;

    public class PeopleDisplayVisitor implements PeopleVisitor {
    @Override
    public void visit(PeopleAwake peopleAwake) {
    System.out.println("peopleAwake...");
    }

    @Override
    public void visit(PeopleEat peopleEat) {
    System.out.println("peopleEat...");
    }

    @Override
    public void visit(PeopleSleep peopleSleep) {
    System.out.println("peopleSleep...");
    }
    }
  4. 完成上述步骤,我们就可以开始演示了

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    package test.visitor;

    import java.util.ArrayList;
    import java.util.List;

    public class VisitorDemo {
    private static List<People> peoples = new ArrayList<>();

    static void action(PeopleVisitor peopleVisitor) {
    peoples.add(new PeopleAwake());
    peoples.add(new PeopleEat());
    peoples.add(new PeopleSleep());
    for (int i = 0; i < peoples.size(); i++) {
    peoples.get(i).action(peopleVisitor);
    }
    }

    public static void main(String[] args) {
    action(new PeopleDisplayVisitor());
    }
    }

    运行结果:

    1
    2
    3
    peopleAwake...
    peopleEat...
    peopleSleep...
说明:

优点: 1、符合单一职责原则。 2、优秀的扩展性。 3、灵活性。

缺点: 1、具体元素对访问者公布细节,违反了迪米特原则。 2、具体元素变更比较困难。 3、违反了依赖倒置原则,依赖了具体类,没有依赖抽象。

欢迎关注我的其它发布渠道