[設計模式]訪問者模式

在訪問者模式(Visitor Pattern)中,我們使用了一個訪問者類,它改變了元素類的執行算法。通過這種方式,元素的執行算法可以隨着訪問者改變而改變。這種類型的設計模式屬於行爲型模式。根據模式,元素對象已接受訪問者對象,這樣訪問者對象就可以處理元素對象上的操作。


意圖

主要將數據結構與數據操作分離。


實現

  • 抽象訪問者
    //抽象訪問者
    public interface Vistor{
        void visit(ElementA element);
        void visit(ElementB element);
        void visit(ElementC element);
        void visit(ElementAll element);
    }
  • 實現訪問者
    //具體訪問者
    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");

        }
    }
  • 抽象元素
    //抽象元素
    public interface Element{
        void accept(Vistor vistor);
    }
  • 實現元素
    //具體元素
    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);
        }
    }
  • 使用
    public void main(String... args){
        ElementAll elementAll = new ElementAll();
        elementAll.accept(new DisplayVisitor());
    }
  • 結果
I/System.out: visit ElementA
I/System.out: visit ElementB
I/System.out: visit ElementC
I/System.out: visit Element Other

資料

菜鳥教程


發佈了88 篇原創文章 · 獲贊 34 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章