Visitor Pattern solution: few visitors have same interface but should work with different objects

前端 未结 4 1059
梦毁少年i
梦毁少年i 2021-01-20 04:31

I have following class diagram (visitor pattern implementation):

Expected result:
1) WiredVisitor should visit only Router and WiredNetworkCard
2)

4条回答
  •  误落风尘
    2021-01-20 04:59

    you can just define some interfaces and slap one on each of the sets of elements that you want it to visit...the advantages of doing it this way are:

    • it is type safe
    • no runtime checks (since they're not needed); no runtime exceptions

    here is an implementation of what i'm talking about for your example:

    • visitors:

      interface  Wired {
           R accept(Visitor v);
      
          interface Visitor {
              R visit(Router router);
      
              R visit(WiredNetworkCard wiredNetworkCard);
          }
      }
      
      interface Wireless {
           R accept(Visitor v);
      
          interface Visitor {
              R visit(Router router);
      
              R visit(WirelessNetworkCard wirelessNetworkCard);
          }
      }
      
    • elements:

      class Router implements Wired, Wireless {
          @Override
          public  R accept(Wired.Visitor v) {
              return v.visit(this);
          }
      
          @Override
          public  R accept(Wireless.Visitor v) {
              return v.visit(this);
          }
      }
      
      class WiredNetworkCard implements Wired {
          @Override
          public  R accept(Wired.Visitor v) {
              return v.visit(this);
          }
      }
      
      class WirelessNetworkCard implements Wireless {
          @Override
          public  R accept(Wireless.Visitor v) {
              return v.visit(this);
          }
      }
      

提交回复
热议问题