[디자인 패턴] ChainOfResponsibility 패턴

이멀젼씨

·

2020. 3. 19. 13:42

- 정의

 

요청이 들어올때 해당 요청을 처리할 수 없는 경우 다음 객체에게 문제를 넘김으로써 최종적으로 요청을 처리할 수 있도록 하는 패턴이다

 

- UML

1. Exception추상클래스를 생성한다

 - Exception배열을 생성하여 4가지 Exception을 넣어준다

 - Exception을 받아온 뒤 어떤 예외인지 찾기위해 next메소드를 수행하는 findError메소드

 - Exception을 받아 현재 배열에 들어있는 예외들과 일치하는게 있으면 해당 Exception클래스를 반환하고 일치하는게 없으면 콘솔에 null을 반환하는 next메소드

 - 파라미터로 받은 에러의 이름과 현재 클래스의 이름이 같은지 확인하는 check메소드 

2. NullPointException, RuntimeException, ClassNotFoundException, IOException클래스는 Excetpion추상클래스의 check메소드를 오버라이딩하여 현재 클래스의 이름과 일치하면 현재 클래스를 반환하고 일치하지 않으면 next메소드를 호출하여 인자로 받아온 Exception인스턴스를 다음 Exception클래스에 넘겨준다

 

- 코드

 

Exception abstract class

public abstract class Exception {
	static Exception[] exceptions = {
			new ClassNotFoundException(), 
			new IOException(), 
			new NullPointException(),
			new RuntimeException()};
	public static int num = 0;
	public static final int max = 3;
	public static Exception exception;
	
	public static Exception findError(Exception exception) {
		return next(exception);
	}
	
	public static Exception next(Exception e) {
		exception = e;
		
		if(num>max) {
			System.out.println("해당 에러에 맞는 타입이 존재하지 않습니다");
			return null;
		}
		
		return exceptions[num++].check();
					
	}
	
	public abstract Exception check();
}

IOException class

public class IOException extends Exception {
	@Override
	public Exception check() {
		if(this.getClass().getName().equals(exception.getClass().getName())) {
			num = 0;
			System.out.println("IOException Occured");
			return this;
		}
		return next(exception);
	}
}

RuntimeException class

public class RuntimeException extends Exception {
	@Override
	public Exception check() {
		if(this.getClass().getName().equals(exception.getClass().getName())) {
			num = 0;
			System.out.println("RuntimeException Occured");
			return this;
		}
		return next(exception);
	}
}

ClassNotFoundException class

public class ClassNotFoundException extends Exception {
	@Override
	public Exception check() {
		if(this.getClass().getName().equals(exception.getClass().getName())) {
			num = 0;
			System.out.println("ClassNotFoundException Occured");
			return this;
		}
		return next(exception);
	}
}

NullPointException class

public class NullPointException extends Exception {
	@Override
	public Exception check() {
		if(this.getClass().getName().equals(exception.getClass().getName())) {
			num = 0;
			System.out.println("NullPointException Occured");
			return this;
		}
		return next(exception);
	}
}

ABCException class

public class ABCException extends Exception {

	@Override
	public Exception check() {
		// TODO Auto-generated method stub
		return null;
	}

}

Main class

public class Main {
	public static void main(String[] args) {
		System.out.println("=====Error occured=====");
		Exception.findError(new RuntimeException());
		Exception.findError(new IOException());
		Exception.findError(new ABCException());
	}
}

출력결과

더보기

=====Error occured=====
RuntimeException Occured
IOException Occured
해당 에러에 맞는 타입이 존재하지 않습니다

 

- 설명

RuntimeException과 IOException을 생성하여 인자로 넘겨주면 무슨 Exception인지 출력이 잘 된다

 

하지만 ABCException은 Exception의 배열안에 포함되어 있지 않으므로 전달해주어도 타입에 맞는 Exception을 출력하지 못한다

 

자바에서 흔히 처리되는 예외처리과정이 책임사슬패턴으로 처리되며 위의 예제는 이를 간단하게 구현해본 것이다

 

장점 : 객체간의 결합도가 낮아진다

 

단점 : 요청이 처리된다는 보장이 없다

 

 

'디자인패턴' 카테고리의 다른 글

[디자인 패턴] Observer 패턴  (0) 2020.03.22
[디자인 패턴] Facade 패턴  (0) 2020.03.20
[디자인 패턴] Visitor 패턴  (0) 2020.03.17
[디자인 패턴] Decorator 패턴  (0) 2020.03.15
[디자인 패턴] Composite 패턴  (0) 2020.03.13