Skip to main content
 首页 » 编程设计

Java 访问者模式

2022年07月19日135JustinYoung

1.访问者模式简介

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

关键代码:在数据基础类里面有一个方法接受访问者,将自身引用传入访问者。

应用实例:老师家访,父亲Tom接待。

2.示例Demo

interface FamilyMember { 
    void accept(Visitor visitor); 
} 
 
class Wife implements FamilyMember { 
    public void accept(Visitor visitor) { 
        visitor.sayHello(this); 
    } 
} 
 
class Daughter implements FamilyMember { 
    public void accept(Visitor visitor) { 
        visitor.sayHello(this); 
    } 
} 
 
class Son implements FamilyMember { 
    public void accept(Visitor visitor) { 
        visitor.sayHello(this); 
    } 
} 
 
 
class Reception implements FamilyMember { 
    private String name; 
    private FamilyMember members[]; 
    public Reception(String name) { 
        this.name = name; 
        members = new FamilyMember[] {new Wife(), new Daughter(), new Son()}; //Attention here 
    } 
 
    public String getName() { 
        return name; 
    } 
 
    public void accept(Visitor visitor) { 
        visitor.sayHello(this); 
        for (FamilyMember member : members) { 
            member.accept(visitor); 
        } 
    } 
} 
 
/*对每一个家庭成员的访问方法可能由于访问者的不同而不同*/ 
interface Visitor { 
    void sayHello(Reception reception); 
    void sayHello(Wife wife); 
    void sayHello(Daughter daughter); 
    void sayHello(Son son); 
} 
 
 
class Teacher implements Visitor { 
    private String receptionName; 
 
    public void sayHello(Reception reception) { 
        receptionName = reception.getName(); 
        System.out.println("Hello " + receptionName); 
    } 
    public void sayHello(Wife wife) { 
        System.out.println("Hello " + receptionName + "'s wife"); 
    } 
    public void sayHello(Daughter daughter) { 
        System.out.println("Hello " + receptionName + "'s daughter"); 
    } 
    public void sayHello(Son son) { 
        System.out.println("Hello " + receptionName + "'s son"); 
    } 
} 
 
 
public class VisitorPatternDemo { 
    public static void main(String args[]) { 
        Visitor visitor = new Teacher(); 
        FamilyMember reception = new Reception("Tom"); 
        reception.accept(visitor); 
    } 
} 
 
/* 
# java VisitorPatternDemo 
Hello Tom 
Hello Tom's wife 
Hello Tom's daughter 
Hello Tom's son 
*/

参考:http://www.runoob.com/design-pattern/visitor-pattern.html


本文参考链接:https://www.cnblogs.com/hellokitty2/p/10742906.html
阅读延展