1. 程式人生 > >java23種設計模式-訪問者模式

java23種設計模式-訪問者模式

定義

封裝一些作用於某種資料結構中各元素的操作,它可以在不改變這個資料結構的前提下定義作用於這些元素的新的操作。

UML

角色

  • Visitor : 抽象訪問者介面
  • Element : 被訪問元素介面
  • ElementA,ElementB : 具體元素,實現了Element介面
  • VisitorA,VisitorB : 具體訪問者,實現了Visitor介面
  • ObjectStruct : 物件結構管理類,是一個較高層的結構

示例


/**
 * desc : 元素介面
 * Created by tiantian on 2018/9/14
 */
public interface
Element {
void accept(Visitor visitor); }
/**
 * desc : 元素A
 * Created by tiantian on 2018/9/14
 */
public class ElementA implements Element {

    private String property1 = "Hello ";

    private String property2 = "World";
    @Override
    public void accept(Visitor visitor) {
        visitor.visit(this
); System.out.println(visitor.getName() + " visited ElementA"); } public String getProperty1() { return property1; } public String getProperty2() { return property2; } }

/**
 * desc : 元素B
 * Created by tiantian on 2018/9/14
 */
public class ElementB implements
Element {
private String property1 = "hello "; private String property2 = "world"; @Override public void accept(Visitor visitor) { visitor.visit(this); System.out.println(visitor.getName() + " visited ElementB"); } public String getProperty1() { return property1; } public String getProperty2() { return property2; } }
/**
 * desc : 訪問者介面
 * Created by tiantian on 2018/9/14
 */
public interface Visitor {

    String getName();

    void visit(ElementA e);

    void visit(ElementB e);
}
/**
 * desc : 具體訪問者A
 * Created by tiantian on 2018/9/14
 */
public class VisitorA implements Visitor {

    private String name = "visitorA";

    @Override
    public String getName() {
        return name;
    }

    @Override
    public void visit(ElementA e) {
        System.out.println(e.getProperty1() + e.getProperty2());
    }

    @Override
    public void visit(ElementB e) {
        System.out.println(e.getProperty1() + e.getProperty2());
    }
}

/**
 * desc : 訪問者B
 * Created by tiantian on 2018/9/15
 */
public class VisitorB implements Visitor{
    private String name = "VisitorB";
    @Override
    public String getName() {
        return name;
    }

    @Override
    public void visit(ElementA e) {
        System.out.println(e.getProperty1() + e.getProperty2());
    }

    @Override
    public void visit(ElementB e) {
        System.out.println(e.getProperty1() + e.getProperty2());
    }
}
/**
 * desc : 物件結構
 * Created by tiantian on 2018/9/14
 */
public class ObjectStruct {

    private List<Element> elements = new ArrayList<>();

    public void add(Element e) {
        elements.add(e);
    }

    public void show(Visitor visitor) {
        for (Element e : elements) {
            e.accept(visitor);
        }
    }
}

總結

訪問者模式使資料結構物件和操縱資料結構的物件分離,從而降低了它們之間的耦合性。可以靈活的新增不同的訪問者,以不同的方式訪問該資料結構的各個元素。缺點是資料結構必須穩定,不能隨意增加元素型別。也就是在示例中,Element元素的具體結構型別數量是恆定的且穩定的;若不穩定,增加了元素型別時,訪問者介面也要發生變化,不符合開閉原則。