访问者模式15(19)

将数据结构和数据访问分离。

数据结构就是Compute类。

 

双分派,客户端传入参数(第一次分派),接受访问者将自己作为参数传给访问者(第二次分派)。

双分派也就是两次状态的改变,简单理解,ComputerVisitor(接收访问者)在客户端接收参数,并将自己传给服务端的访问者访问。

package behavioral.visit;

public interface ComputerPart {

    public void accept(ComputerVisitor v);
}

package behavioral.visit;

public class Mouse implements ComputerPart {

    @Override
    public void accept(ComputerVisitor v) {
        v.visit(this);
    }

}

package behavioral.visit;

public class Keyboard implements ComputerPart {

    @Override
    public void accept(ComputerVisitor v) {
        v.visit(this);
    }

}

package behavioral.visit;

public class Monitor implements ComputerPart {

    @Override
    public void accept(ComputerVisitor v) {
        v.visit(this);
    }

}

package behavioral.visit;

public class Computer implements ComputerPart{

    ComputerPart[] parts;
     
       public Computer(){
          parts = new ComputerPart[] {new Mouse(), new Keyboard(), new Monitor()};      
       } 
     
     
       @Override
       public void accept(ComputerVisitor v) {
          for (int i = 0; i < parts.length; i++) {
             parts[i].accept(v);
          }
          v.visit(this);
       }
}

 

package behavioral.visit;

public interface Visitor {

    public void visit(Computer c);
    public void visit(Mouse mou);
    public void visit(Keyboard k);
    public void visit(Monitor mon);

}


package behavioral.visit;

public class ComputerVisitor implements Visitor {

    @Override
    public void visit(Computer c) {
        System.out.println("The computer is on");
    }

    @Override
    public void visit(Mouse mou) {
        System.out.println("click mouuse");
    }

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

    @Override
    public void visit(Monitor mon) {
        System.out.println("The monitor has a picture");
    }

}

package behavioral.visit;

public class VisitMan {

    public static void main(String[] args) {
        ComputerPart computer = new Computer();
        computer.accept(new ComputerVisitor());
    }

}

 

posted @ 2019-08-29 11:33  飞鸟游鱼  阅读(131)  评论(0编辑  收藏  举报