You will be fine

<디자인패턴입문> 11. Chain of Responsibility 패턴

by BFine
반응형

www.yes24.com/Product/Goods/2918928

 

Java 언어로 배우는 디자인 패턴 입문

이 책은 디자인 패턴의 입문서입니다. GoF가 정리한 23개의 디자인 패턴을 하나씩 다루면서 객체 지향을 잘 모르는 초보자도 이해하기 쉽도록 정리하고 있습니다. 단순한 이론이나 논리을 제시하

www.yes24.com

 

가. 무엇인가

 a. 책임 떠넘기기!

  -  담당부서 부서의 담당자를 찾을때까지 자신의 요구가 차례로 넘겨지는 것이 책임 떠넘기기

  -  어떤 요청이 발생했을때 그 요청을 처리할 객체를 바로 결정할 수 없는 경우 

      복수의 객체를 체인처럼 연결해두어서 차례로 탐색하면서 처리를 결정하는 방법이다.

 

 b. 요청과 처리를 분리하자!

  -  요청하는 쪽과 처리하는 쪽의 연결을 유연하게 해서 각 객체를 부품으로 독립 시킬 수 있다.

  -  요구를 하면 처리할 수 없으면 다음 사람에게 넘기고 처리 할 수 있으면 처리하도록 한다.

 

나. 만들어본 예제

학생이 어떤 교실에 있는지 출력하는 예제

 a. Handler (처리자) 역할

  -  요구를 처리하는 인터페이스를 결정하는 역할을 한다. 처리 객체를 하나로 보게하는 역할이다.

  -  추상클래스로 구현하며 다음 요구를 받을 처리 객체를 가지고 있어야 한다.

public abstract class LectureChain {
    protected static Map<String,String> roomMap = new HashMap<>();
    private LectureChain next;

    public LectureChain setNext(LectureChain next) {
        this.next = next;
        return next;
    }
    public void participateIn(Student student) {
        if (listen(student)) {
            System.out.println(student.getName()+"가 
            					"+student.getLecture()+"수업에 들어갑니다.");
        } else if (next != null) {
            next.participateIn(student);
        }
    }

    public abstract boolean listen(Student student);

    public static void print(){
        roomMap.forEach((k,v)-> System.out.println(k+"는 "+v+"에 있습니다."));
    }
}

 b. ConcreteHandler (구체적인 처리자) 역할

  -  구체적인 처리역할을 담당하며 각각 개별적인 처리를 가질 수 있다.

public class Ethics extends LectureChain{
    String room;

    public Ethics(String room) {
        this.room = room;
    }

    @Override
    public boolean listen(Student student) {
        if("Ethics".equals(student.getLecture())){
            roomMap.put(student.getName(),room);
            return true;
        }
        return false;
    }
}


public class Science extends LectureChain {
    String room;

    public Science(String room) {
        this.room = room;
    }

    @Override
    public boolean listen(Student student) {
        if("Science".equals(student.getLecture())){
            roomMap.put(student.getName(),room);
            return true;
        }
        return false;
    }
}


public class Social extends LectureChain {
    String room;

    public Social(String room) {
        this.room = room;
    }

    @Override
    public boolean listen(Student student) {
        if("Social".equals(student.getLecture())){
            roomMap.put(student.getName(),room);
            return true;
        }
        return false;
    }
}

 c. Main (Client 역할)

public class Main {

    public static void main(String[] args) {
        Ethics ethics = new Ethics("201");
        Science science = new Science("301");
        Social social = new Social("101");
        Student student1 = new Student("철수", "Ethics");
        Student student2 = new Student("영희","Ethics");
        Student student3 = new Student("준희","Social");
        Student student4 = new Student("민호", "Science");
        Student student5 = new Student("소희","Ethics");

        List<Student> studentList = new ArrayList<>();
        studentList.add(student1);
        studentList.add(student2);
        studentList.add(student3);
        studentList.add(student4);
        studentList.add(student5);

        ethics.setNext(science).setNext(social);

        for (Student student: studentList) {
            ethics.participateIn(student);
        }

        LectureChain.print();
    }
}

/**
"C:\Program Files\Java\jdk-11.0.8\bin\java.exe" 
철수가 Ethics수업에 들어갑니다.
영희가 Ethics수업에 들어갑니다.
준희가 Social수업에 들어갑니다.
민호가 Science수업에 들어갑니다.
소희가 Ethics수업에 들어갑니다.
철수는 201에 있습니다.
영희는 201에 있습니다.
준희는 101에 있습니다.
소희는 201에 있습니다.
민호는 301에 있습니다.
*/

다. 정리

 a. 요구와 처리를 유연하게 연결!

  -  Client와 ConcreteHandler를 유연하게 연결하는것이 포인트이다. 뒷일이 사슬처럼 연결되어 처리된다.

  -  요구 객체가 처리 객체들의 분담까지 자세하게 알아야 한다면 부품으로써 독립성이 훼손된다.

 

 b. 동적으로 사슬 형태를 바꾼다.

  -  상황의 변화에 따라서 ConcreteHandler 역할을 재편할수가 있다.

 

 c. 떠넘기기로 처리가 지연되지 않을까?

  -  요구 처리가 명확하게 된 것과 비교하면 이 떠넘기기 패턴이 처리는 지연되지만 그만큼 유연성을 가지고 있다.

Chain of Responsibility 패턴은 요청 객체와 처리 객체를 분리하며 처리 객체는 체인 형태로 구성하여
요청 객체에 맞는 처리객체가 나올때까지 탐색하여 처리하는 유연성을 가진 패턴이다.
반응형

블로그의 정보

57개월 BackEnd

BFine

활동하기