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

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

      The Command pattern is a behavioral design pattern in which an object is used to encapsulate all information needed to perform an action or trigger an event at a later time.

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

      Command Pattern
  2. Example
    • The Receiver:

      public interface Payment {
          void apply();
      }

    • The Concrete Receiver:

      • Implementation 1:

        public class Debit implements Payment {
            public void apply() {
                System.out.println("debit ...");
            }
        }

      • Implementation 2:

        public class Credit implements Payment {
            public void apply() {
                System.out.println("credit ...");
            }
        }

    • The Command:

      public interface Transaction {
          void apply();
      }

    • The Concrete Command:

      public class TransactionImpl implements Transaction {
          private Payment payment;
      
          public TransactionImpl(final Payment payment) {
              this.payment = payment;
          }
      
          public void apply() {
              payment.apply();
          }
      }

    • The Caller:

      public class Operator {
          private Transaction transaction;
      
          public void setTransaction(final Transaction transaction) {
              this.transaction = transaction;
          }
      
          public void apply() {
              transaction.apply();
          }
      }

    • A simple class to test the Command design pattern:

      public class CommandPatternTest {
          public static void main(String[] args) {
              // create the payment
              Payment payment = new Debit();
      
              // create the transaction
              Transaction transaction = new TransactionImpl(payment);
      
              // create the operator
              Operator operator = new Operator();
      
              operator.setTransaction(transaction);
      
              // call methods
              operator.apply();
          }
      }

© 2025  mtitek