23种设计模式之访问者模式-2. 代码

2.1 ComputerPartVisitor (访问者接口)

public interface ComputerPartVisitor {
    void visit(Keyboard keyboard);
    void visit(Mouse mouse) ;
    void visit(Monitor mouse) ;
    void visit(Computer computer) ;
}

2.2 ComputerDisplayVisitor(具体访问者)

public class ComputerDisplayVisitor implements ComputerPartVisitor{
    @Override
    public void visit(Computer computer) {
        System.out.println("Displaying Computer");
    }
    @Override
    public void visit(Keyboard keyboard) {
        System.out.println("Displaying Keyboard");
    }
    @Override
    public void visit(Monitor monitor) {
        System.out.println("Displaying Monitor");
    }
    @Override
    public void visit(Mouse mouse) {
        System.out.println("Displaying Mouse");
    }
}

2.3 ComputerPart (元素接口)

public interface ComputerPart {
    public void accept(ComputerPartVisitor computerPartVisitor) ;
}

2.4 Mouse (具体元素)

public class Mouse implements ComputerPart{
    @Override
    public void accept(ComputerPartVisitor computerPartVisitor) {
        computerPartVisitor.visit(this);
    }
}

2.5 Monitor(具体元素)

public class Monitor implements ComputerPart{
    @Override
    public void accept(ComputerPartVisitor computerPartVisitor) {
        computerPartVisitor.visit(this);
    }
}

2.6 Keyboard (具体元素)

public class Keyboard implements ComputerPart{
    @Override
    public void accept(ComputerPartVisitor computerPartVisitor) {
        computerPartVisitor.visit(this);
    }
}

2.7 Computer (对象结构类)

public class Computer implements ComputerPart{
    ComputerPart[] parts;

    public Computer(){
        parts = new ComputerPart[] {new Mouse(), new Keyboard(), new Monitor()};
    }

    @Override
    public void accept(ComputerPartVisitor computerPartVisitor) {
        for (ComputerPart part : parts) {
            part.accept(computerPartVisitor);
        }
        computerPartVisitor.visit(this);
    }
}

2.8 Test (测试类)

public class Test {
    public static void main(String[] args) {

        ComputerPart computer = new Computer();
        computer.accept(new ComputerDisplayVisitor());

    }
}

2.9 运行结果

Displaying Mouse
Displaying Keyboard
Displaying Monitor
Displaying Computer
上一篇:删除Yocto中build-x9hp_ms_a12_vemmc_ap2/tmp/work/aarch64-sdrv-linux/package后再编译出错问题


下一篇:etcd常见运维事件