Design pattern - behavioral pattern explanation I (responsibility chain, command, iterator)

1, Behavioral design pattern

In the first part, we explained the structural design patterns, including adapter pattern, bridge pattern, combination pattern, decorator pattern, element sharing pattern, agent pattern and appearance pattern.

Adapter, bridge, combination and sharing element: https://blog.csdn.net/qq_43692950/article/details/120248267
Decorator, appearance and agent: https://blog.csdn.net/qq_43692950/article/details/120249265

In this article, let's explain the following behavioral design pattern: it is mainly used to describe the interaction or responsibility allocation between classes or objects, and to guide the interaction and responsibility allocation of design classes.

This paper mainly introduces: responsibility chain, command and iterator mode.

2, Responsibility chain model

The Chain of Responsibility Pattern creates a chain of receiver objects for requests. This mode gives the type of request and decouples the sender and receiver of the request.

In this pattern, each recipient usually contains a reference to another recipient. If an object cannot process the request, it passes the same request to the next recipient, and so on.

The advantage is to reduce the coupling degree, which decouples the sender and receiver of the request. The object is simplified so that the object does not need to know the structure of the chain. Enhance the flexibility of assigning responsibilities to objects, and allow dynamic addition or deletion of responsibilities by changing the members in the chain or transferring their order. It is convenient to add new request processing classes.

For example, in normal development, we often need to print logs to view some information, but when we print logs, we will specify a log level, such as INFO, WARN, ERROR, etc. the files stored in the logs printed at different levels are different. This scenario can be designed and solved using the responsibility chain design mode.

The following procedure is used to demonstrate the above example:

  1. Define log interface
public interface LoggerInterFace {
    //Specify next target
    void setNextLogger(LoggerInterFace nextLogger);
    //Print log
    void logMessage(int level, String message);
    //Log format
    void writeFormat(String message);
}
  1. Define log abstract template
public abstract class AbstractLogger implements LoggerInterFace {
    public static int INFO = 1;
    public static int WARN = 2;
    public static int ERROR = 3;

    private int level;
    private LoggerInterFace nextLogger;

    public AbstractLogger(int level) {
        this.level = level;
    }

    @Override
    public void setNextLogger(LoggerInterFace nextLogger) {
        this.nextLogger = nextLogger;
    }

    @Override
    public void logMessage(int level, String message) {
        if (this.level == level) {
            writeFormat(message);
        }
        if (nextLogger != null) {
            nextLogger.logMessage(level, message);
        }
    }

}
  1. Define the implementation of the Info level
public class InfoLogger extends AbstractLogger {

   public InfoLogger(int level) {
      super(level);
   }

   @Override
   public void writeFormat(String message) {
      System.out.println(StringFormatter.concat(" General information:", message).getValue());
   }

}
  1. Define the implementation of the Warn level
public class WarnLogger extends AbstractLogger {

   public WarnLogger(int level) {
      super(level);
   }

   @Override
   public void writeFormat(String message) {
      System.out.println(StringFormatter.concat(" Warning message:", message).getValue());
   }
}
  1. Define the implementation of the Error level
public class ErrorLogger extends AbstractLogger {

    public ErrorLogger(int level) {
        super(level);
    }

    @Override
    public void writeFormat(String message) {
        System.out.println(StringFormatter.concat(" Error message:", message).getValue());
    }
}
  1. Define the log factory and the order of the responsibility chain
public class LoggerFactory {

    public static LoggerInterFace getLogger() {
        //Define the sequence of responsibility chains
        List<AbstractLogger> list = new LinkedList<>();
        list.add(new ErrorLogger(AbstractLogger.ERROR));
        list.add(new WarnLogger(AbstractLogger.WARN));
        list.add(new InfoLogger(AbstractLogger.INFO));

        for (int i = 0; i < list.size() - 1; i++) {
            list.get(i).setNextLogger(list.get(i + 1));
        }

        return list.get(0);
    }
}
  1. demonstration
public class demo {
    public static void main(String[] args) {
        LoggerInterFace logger = LoggerFactory.getLogger();

        logger.logMessage(AbstractLogger.INFO, " Print general log");

        logger.logMessage(AbstractLogger.WARN, " Print warning log");

        logger.logMessage(AbstractLogger.ERROR, " Print error log");
    }
}

Tags: Design Pattern

Posted on Tue, 21 Sep 2021 17:21:12 -0400 by Nandini