Visitor pattern implementation in case of source code un-availability

前端 未结 6 1603
旧时难觅i
旧时难觅i 2021-01-04 21:48

One of the reasons to consider the Visitor_pattern:

A practical result of this separation is the ability to add new operations to existing object structu

6条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-04 22:11

    If your library does not has accept methods you need to do it with instanceof. (Normally you do twice single-dispatching in Java to emulate double dispatching; but here we use instanceof to emulate double dispatching).

    Here is the example:

    interface Library {
      public void get1();
      public void get2();
    }
    
    public class Library1 implements Library {
      public void get1() { ... }
      public void get2() { ... }
    }
    
    public class Library2 implements Library {
      public void get1() { ... }
      public void get2() { ... }
    }
    
    interface Visitor {
       default void visit(Library1 l1) {}
       default void visit(Library2 l2) {}
    
       default void visit(Library l) {
          // add here instanceof for double dispatching
          if (l instanceof Library1) {
              visit((Library1) l);
          }
          else if (l instanceof Library2) {
              visit((Library2) l);
          }
       }
    }
    
    // add extra print methods to the library
    public class PrinterVisitor implements Visitor {
       void visit(Library1 l1) {
           System.out.println("I am library1");
       } 
       void visit(Library2 l2) {
           System.out.println("I am library2");
       }        
    }
    

    and now in any method you can write:

    Library l = new Library1();
    PrinterVisitor pv = new PrinterVisitor();
    pv.visit(l);
    

    and it will print to you "I am library1";

提交回复
热议问题