An introduction to the responsibility chain pattern of Java design patterns

  • 2020-04-01 03:24:49
  • OfStack

For those of you who have used macros, macros can be used to bind multiple skills to one key. For example, if the first skill has a CD, this skill is skipped and the next skill is executed. Remember once played DK, when playing strange, is to use a key, has been pressed on the line. With the doGet and doPost methods in servlets, we generally send doGet requests to doPost for processing, which is also a pattern of responsibility chain.

Here, there is a macro that binds two abilities, "icy blood cold veins" and "icy arrow", the program example is as follows:


package responsibility;


public interface ISkill {

  public void castSkill();

}

package responsibility;

import java.util.ArrayList;
import java.util.List;


public class Macro {

  
  public List<ISkill> skills = new ArrayList<ISkill>();

  
  public void castSkill() {
    for (int i = 0; i < skills.size(); i++) {
      skills.get(i).castSkill();
    }
  }

  
  public void bindSkill(ISkill skill) {
    skills.add(skill);
  }

}

package responsibility;


public class IceArrow implements ISkill {

  @Override
  public void castSkill() {
    System.out.println(" cast -- Frostbolt" ");
  }

}

package responsibility;


public class IceBloodFast implements ISkill {

  @Override
  public void castSkill() {
    //This can be used to determine whether the skill is cooling down or not
    System.out.println(" cast -- Cold blood cold pulse ");
  }

}

The test class:


package responsibility;

public class Main {

  public static void main(String[] args) {
    Macro macro = new Macro();
    macro.bindSkill(new IceBloodFast());
    macro.bindSkill(new IceArrow());
    macro.castSkill();
  }

}

Test results:


 Is cast -- Cold blood cold pulse 
 cast -- Frostbolt" 

Conclusion: The chain of responsibility pattern is primarily used in cases where a request may have multiple objects to process.


Related articles: