• Home
  • LLMs
  • Docker
  • Kubernetes
  • Java
  • All
  • About
Design Patterns | Visitor
  1. References
  2. Example
    • The Visitor
    • The Concrete Visitor
    • The Element
    • The Concrete Element
    • A simple class to test the Visitor design pattern

  1. References
    • Definition: (source: http://en.wikipedia.org/wiki/Visitor_pattern)

      The visitor design pattern is a way of separating an algorithm from an object structure on which it operates.
      A practical result of this separation is the ability to add new operations to existing object structures without modifying those structures.

    • Class diagram: (source: http://en.wikipedia.org/wiki/Visitor_pattern)

      Visitor Pattern
  2. Example
    • The Visitor:

      public interface Visitor {
          void visit(final Debit debit);
      
          void visit(final Credit credit);
      }

    • The Concrete Visitor:

      public class VisitorImpl implements Visitor {
          public void visit(final Debit debit) {
              System.out.println("Visit Debit ...");
          }
      
          public void visit(final Credit credit) {
              System.out.println("Visit Credit ...");
          }
      }

    • The Element:

      public interface Payment {
          void accept(final Visitor visitor);
      }

    • The Concrete Element:

      • Implementation 1:

        public class Debit implements Payment {
            public void accept(final Visitor visitor) {
                visitor.visit(this);
            }
        }

      • Implementation 2:

        public class Credit implements Payment {
            public void accept(final Visitor visitor) {
                visitor.visit(this);
            }
        }

    • A simple class to test the Visitor design pattern:

      public class VisitorPatternTest {
          public static void main(String[] args) {
              final Payment debit = new Debit();
              final Payment credit = new Credit();
      
              final Visitor visitor1 = new VisitorImpl();
      
              debit.accept(visitor1);
              credit.accept(visitor1);
          }
      }

© 2025  mtitek