[design mode] visitor mode

In Visitor Pattern, we use a visitor class, which changes the execution algorithm of element class. In this way, the execution algorithm of the element can change as the visitor changes. This type of design pattern belongs to behavioral pattern. According to the pattern, the element object has accepted the accessor object, so that the accessor object can handle operations on the element object.

intention

It mainly separates data structure from data operation.

Realization

  • Abstract Visitor
    //Abstract Visitor 
    public interface Vistor{
        void visit(ElementA element);
        void visit(ElementB element);
        void visit(ElementC element);
        void visit(ElementAll element);
    }
  • Implement visitors
    //Specific visitors
    public class DisplayVisitor implements Vistor{

        @Override
        public void visit(ElementA element) {
            System.out.println("visit ElementA");

        }

        @Override
        public void visit(ElementB element) {
            System.out.println("visit ElementB");

        }

        @Override
        public void visit(ElementC element) {
            System.out.println("visit ElementC");

        }

        @Override
        public void visit(ElementAll element) {
            System.out.println("visit Element Other");

        }
    }
  • Abstract elements
    //Abstract elements
    public interface Element{
        void accept(Vistor vistor);
    }
  • Implementation elements
    //Specific elements
    public class ElementA implements Element{

        @Override
        public void accept(Vistor vistor) {
            vistor.visit(this);
        }
    }

    public class ElementB implements Element{

        @Override
        public void accept(Vistor vistor) {
            vistor.visit(this);
        }
    }

    public class ElementC implements Element{

        @Override
        public void accept(Vistor vistor) {
            vistor.visit(this);
        }
    }

    public class ElementAll implements Element{
        private Element[] elements;

        public ElementAll() {
            this.elements = new Element[]{new ElementA(),new ElementB(),new ElementC()};
        }

        @Override
        public void accept(Vistor vistor) {
            for (Element element : elements) {
                element.accept(vistor);
            }
            vistor.visit(this);
        }
    }
  • Use
    public void main(String... args){
        ElementAll elementAll = new ElementAll();
        elementAll.accept(new DisplayVisitor());
    }
  • Result
I/System.out: visit ElementA
I/System.out: visit ElementB
I/System.out: visit ElementC
I/System.out: visit Element Other

data

Rookie tutorial

Posted on Thu, 30 Apr 2020 18:34:16 -0700 by RP