zno2

25) Visitor pattern

类别:

 Behavior Pattern

visit ['vizit]  the act of going to see some person or place or thing for a short time

问题:

 

方案:

 

示例:

public class VisitorPatternDemo {
    public static void main(String[] args) {
        
        Visitor visitor = new ComputerPartVisitor();
        
        Mouse mouse = new Mouse();
        Keyboard keyboard = new Keyboard();
        Monitor monitor = new Monitor();
        
        mouse.accept(visitor);
        keyboard.accept(visitor);
        monitor.accept(visitor);
    }
}

interface ComputerPart {
    public void accept(Visitor visitor);
}

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

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

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


interface Visitor {

    public void visit(Mouse mouse);

    public void visit(Keyboard keyboard);

    public void visit(Monitor monitor);
}

class ComputerPartVisitor implements Visitor {

    @Override
    public void visit(Mouse mouse) {
        System.out.println("Displaying Mouse.");
    }

    @Override
    public void visit(Keyboard keyboard) {
        System.out.println("Displaying Keyboard.");
    }

    @Override
    public void visit(Monitor monitor) {
        System.out.println("Displaying Monitor.");
    }
}

 

Displaying Mouse.
Displaying Keyboard.
Displaying Monitor.

 

应用:

 

不足:(

 

优化:)

 

posted on 2023-06-09 13:37  zno2  阅读(9)  评论(0编辑  收藏  举报

导航