1

책임 패턴의 체인을 구현하려고하지만 구체적인 클래스에서 setnexthandler가 다음을 설정하지 않기 때문에 항상 누락 된 것으로 보입니다.하지만 항상 동일합니다. 내 실수는 else statems next.setNextHandler (next)에서 processMalfunction() 메서드의 구체적인 클래스에 있다고 생각합니다. 나는 그것이 첫 번째 것에 대한 next.setNextHandler (Severity.Medium)이어야한다고 생각한다. 당신이 볼 수 있다면 여기에 코드가 있습니다. 여기에 코드가 있습니다.책임 패턴의 체인

public interface MalfunctionHandler 
{ 
    public void processMalfunction(Malfunction malfunciton); 
    public void setNextHandler(MalfunctionHandler handler); 
} 

public enum Severity 
{ 
    TRIVIAL, LOW, MEDIUM, HIGH 
} 

public class Malfunction 
{ 
    /** 
    * severity is a type of Severity 
    */ 
    Severity severity; 

    /** 
    * @param description describes the severity of the problem 
    */ 
    String description; 

    Malfunction(Severity severity, String description) 
    { 
     if(description == null) 
     { 
      description = "No description available. Probably serious."; 
     } 

     if(description.isEmpty()) 
     { 
      description = "No description available. Probably serious."; 
     } 

     this.severity = severity; 
     this.description = description; 
    } 

    public Severity getSeverity() 
    { 
     return severity; 
    } 

    public String getDescription() 
    { 
     return description; 
    } 

    public void setSeverity(Severity severity) 
    { 
     this.severity = severity; 
    } 

    public void setDescription(String description) 
    { 
     this.description = description; 
    } 
} 

public class SpaceMonkey implements MalfunctionHandler 
{ 

    Severity severity; 
    MalfunctionHandler next; 
    File read = new File("expected-bronze.txt"); 
    File f = new File("log-bronze.txt"); 

    SpaceMonkey(Severity severity) 
    { 
     this.severity = severity; 
     System.out.println(FileUtility.readFile(read)); 
    } 

    @Override 
    public void processMalfunction(Malfunction malfunction) 
    { 
     if (malfunction.getSeverity() == Severity.LOW) 
     { 
      final String[] splits = FileUtility.readFile(read).split("problem."); 
      for (String asset : splits) 
      { 
       if (asset.contains("Space monkey")) 
       { 
        FileUtility.writeFile(f, asset + "problem."); 
        System.out.println(asset + "problem."); 
       } 
      } 
     } 
     else 
     { 
      next.setNextHandler(next); 
     } 
    } 

    @Override 
    public void setNextHandler(MalfunctionHandler next) 
    { 
     this.next = next; 
    } 
} 

public class ServiceRobot implements MalfunctionHandler 
{ 

    Severity severity; 
    MalfunctionHandler next; 
    File read = new File("expected-bronze.txt"); 
     File f = new File("log-bronze.txt"); 

    ServiceRobot(Severity severity) 
    { 
     this.severity = severity; 
    } 


    @Override 
    public void processMalfunction(Malfunction malfuntion) 
    { 


     if (this.severity == severity) 
     { 
      String[] splits = FileUtility.readFile(read).split("problem."); 
     for(String asset : splits) 
     { 
      if(asset.contains("Service robot")) 
      {     
       FileUtility.writeFile(f, asset + "problem."); 
       System.out.println(asset + "problem."); 

      } 
     } 
     } 
     else 
     { 
      next.setNextHandler(next); 
     } 
    } 

    @Override 
    public void setNextHandler(MalfunctionHandler next) 
    { 
     this.next = next; 
    } 

} 

public class Engineer implements MalfunctionHandler 
{ 

    Severity severity; 
    MalfunctionHandler next; 
    File read = new File("expected-bronze.txt"); 

    Engineer(Severity severity) 
    { 
     this.severity = severity; 
    } 


    @Override 
    public void processMalfunction(Malfunction malfuntion) 
    { 
     File f = new File("log-bronze.txt"); 

     if (this.severity == severity) 
     { 
      String[] splits = FileUtility.readFile(read).split("problem."); 
     for(String asset : splits) 
     { 
      if(asset.contains("Engineer")) 
      { 
       FileUtility.writeFile(f, asset + "problem."); 
       System.out.println(asset + "problem."); 

      } 
     } 
     } 
     else 
     { 
      next.setNextHandler(next); 
     } 
    } 

    @Override 
    public void setNextHandler(MalfunctionHandler next) 
    { 
     this.next = next; 
    } 

} 

public class Captain implements MalfunctionHandler 
{ 
    Severity severity; 
    MalfunctionHandler next; 
    File read = new File("expected-bronze.txt"); 

    Captain(Severity severity) 
    { 
     this.severity = severity; 
    } 
    @Override 
    public void processMalfunction(Malfunction malfuntion) 
    { 
     File f = new File("log-bronze.txt"); 

     if (this.severity == severity) 
     { 
      String[] splits = FileUtility.readFile(read).split("problem."); 
     for(String asset : splits) 
     { 
      if(asset.contains("Captain")) 
      { 
       FileUtility.writeFile(f, asset + "problem."); 
       System.out.println(asset + "problem."); 

      } 
     } 
     } 
     else 
     { 
      next.setNextHandler(next); 
     } 
    } 

    @Override 
    public void setNextHandler(MalfunctionHandler next) 
    { 
     this.next = next; 
    } 

} 

public class FileUtility 
{ 

    /** This method appends a single string to a text file. 
    * 
    * @param f The file to write to 
    * @param entry The string to append 
    */ 
    public static void writeFile(File f, String entry) 
    { 
     try 
     { 
      final BufferedWriter out = new BufferedWriter(new FileWriter(f, true)); 
      out.write(entry); 
      out.close(); 
     } catch (IOException e) 
     { 
      System.err.println("Problem writing to the file"); 
     } 
    } 

    /** This method resets the named text file. 
    * 
    * @param f The file to reset 
    */ 
    public static void resetFile(File f) { 
     try { 
      final BufferedWriter out = new BufferedWriter(new FileWriter(f, false)); 
      out.write(""); 
      out.close(); 
     } catch (IOException e) { 
      System.err.println("Problem reset the file"); 
     } 
    } 

    /** This method reads the contents of a text file. 
    * 
    * @param f The file to read from 
    * @return the contents of the text file as a single string 
    */ 
    public static String readFile(File f) { 
     final StringBuilder sb = new StringBuilder(); 
     try { 
      final Scanner scanner = new Scanner(f); 
      while (scanner.hasNextLine()) { 
       sb.append(scanner.nextLine()); 
      } 
      scanner.close(); 
     } catch (FileNotFoundException e) { 
      System.err.println("Problem reading from file"); 
     } 
     return sb.toString(); 
    } 
} 


public class MalfunctionHandlerTest { 

    /** 
    * No-args constructor. 
    */ 
    public MalfunctionHandlerTest() { 
    } 

    /** 
    * Test of processMalfunction method. 
    */ 
    @Test 
    public void testProcessMalfunction() { 

     // Instanciate malfunction handlers 
     final SpaceMonkey sm = new SpaceMonkey(Severity.TRIVIAL); 
     final ServiceRobot sr = new ServiceRobot(Severity.LOW); 
     final Engineer e = new Engineer(Severity.MEDIUM); 
     final Captain c = new Captain(Severity.HIGH); 

     // Construct chain of responsbility 
     sm.setNextHandler(sr); 
     sr.setNextHandler(e); 
     e.setNextHandler(c); 

     // Create malfunctions 
     final Malfunction m1 = new Malfunction(Severity.HIGH, "Life support error. Oxygen " 
       + "Recycling unit damaged, running at half efficiency");  
     final Malfunction m2 = new Malfunction(Severity.LOW, "Communications error. Cannot " 
       + "find Jazz FM"); 
     final Malfunction m3 = new Malfunction(Severity.MEDIUM, "Power supply error. Solar Panel " 
       + "2 damaged, running at 31.3333% efficiency"); 
     final Malfunction m4 = new Malfunction(Severity.MEDIUM, "Thermal regulation error. Sensor " 
       + "damaged, manual temperature regulation needed"); 
     final Malfunction m5 = new Malfunction(Severity.TRIVIAL, "Trash can full on C-Desk."); 
     final Malfunction m6 = new Malfunction(Severity.LOW, "Shower plug hole full of monkey hair"); 
     final Malfunction m7 = new Malfunction(Severity.HIGH, "Proximity alert. Collision imminent"); 

     // Clean log file 
     FileUtility.resetFile(new File("log-bronze.txt")); 

     // Process malfunctions 
     sm.processMalfunction(m1); 
     sm.processMalfunction(m2); 
     sm.processMalfunction(m3); 
     sm.processMalfunction(m4); 
     sm.processMalfunction(m5); 
     sm.processMalfunction(m6); 
     sm.processMalfunction(m7); 

     // Check log file 
     final String actualOutput = FileUtility.readFile(new File("log-bronze.txt")); 
     final String expectedOutput = FileUtility.readFile(new File("expected-bronze.txt")); 
     assertEquals(actualOutput, expectedOutput); 
    } 
} 

답변

5

여기에 체인 설정이 표시되지 않습니다. 패턴의 원리는 체인의 각 링크가 그 부분을 수행하고 다음 링크를 어떻게 든 호출하는 것입니다. 현재 코드가 일부 경우에 뭔가를하고있는에 구성

Link1 start = new Link1(); 
Link2 link2 = new Link2(); 
start.setNextHandler(link2); 
Link3 link3 = new Link3(); 
link2.setNextHandler(link3); 
... 

같은

public void processMalfunction(Malfunction malfunction) { 
    doSomething(); 
    this.next.processMalfunction(malfunction); 
} 

그리고 물론

, 체인이 설치 전에해야한다, 사용 일 :

그래서 방법은 다음과 같이한다 조건이 참이면 다른 처리기의 다음 처리기를 자체에 할당합니다.

next.setNextHandler(next); 
+0

죄송합니다. 나는 그것이 필연적이지 않다고 가정하고있는 테스트 수업을 제공하지 않았다. 나는 그것을 지금 편집했다. –

+0

내 포인트는 여전히 유효합니다. 링크가 체인의 다음 링크를 호출하지 않습니다. 링크는 체인의 구조를 수정해서는 안되며, 체인의 구조는 그 책임이 아닙니다. –

+1

귀하의 의견에 A Chain이 그 부분을 수행하고 다른 사람에게 전달한다고 언급했지만 더 나은 구현은 Chain이 해당 작업을 수행 할 수없는 경우에만 전달하는 것입니다. 체인이 요청을 처리 할 수 ​​있으면 클라이언트가이를 다시 돌려줍니다. – Atul